Java – Why Generic type can not instantiated

genericsjava

Here is my question.

class Gen<T> {
    T ob;
    Gen() {
        ob = new T(); // Illegal!!!
    }
}

Why is it illegal? Could you please explain it.

Best Answer

This is impossible because of the following 2 reasons.

  1. There is no guarantee that T has a no-args constructor (and for that matter isn't an interface or abstract class)
  2. Due to type erasure (required for backwards compatibility) the Type of T is known at compile time but not at run time, so what to construct wouldn't be known.

An answer may be to take a T factory in the constructor. Then Gen can request new Ts to its heart content.

Related Topic