ProgrammingVery hardIBM · Deloitte pattern
What is wrong with this generic class?
What is wrong with this generic class?
class Factory<T> {
T create() {
return new T();
}
}- A. Nothing; create() returns a new instance of whatever T is at run time
- B. Compile-time error: a type parameter T cannot be instantiated with new
- C. It compiles but throws an InstantiationException at run time
- D. It only fails if T has no public no-arg constructor
Correct answer: B. Compile-time error: a type parameter T cannot be instantiated with new
Because of type erasure, the JVM has no runtime representation of T to instantiate — by the time the method runs, T is just Object. The compiler therefore rejects new T() outright at compile time; this is one of the most common generics restrictions asked about in interviews.
More OOP with C++ and Java questions
- What is printed? java class A { static int x = init("x", 1); static { System.out.print("sA "); } static int y = init("y", 2); static int…
- What is printed? cpp struct Base { virtual void f() { std::cout << "Base "; } }; struct Mid : Base { }; struct Derived : Mid { void f()…
- What is printed? cpp struct Base { Base(){ std::cout << "Base "; } }; struct Mem { Mem(){ std::cout << "Mem "; } }; struct Derived : Base…
- What is printed? cpp struct A { virtual void f() { std::cout << "A::f "; } }; struct B : A { void f() override { std::cout << "B::f "; }…
- Which statement about this program's behaviour is true? cpp struct S { int b; int a; S() : a(1), b(a + 1) { } }; int main() { S s…
- What is printed? java class A { protected int val() { return 1; } } class B extends A { protected int val() { return 2; } } class C…