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();
    }
}
  1. A. Nothing; create() returns a new instance of whatever T is at run time
  2. B. Compile-time error: a type parameter T cannot be instantiated with new
  3. C. It compiles but throws an InstantiationException at run time
  4. 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

Exams that ask this topic