Here is my question.
class Gen<T> {
T ob;
Gen() {
ob = new T(); // Illegal!!!
}
}
Why is it illegal? Could you please explain it.
7
This is impossible because of the following 2 reasons.
- There is no guarantee that T has a no-args constructor (and for that matter isn’t an interface or abstract class)
- 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.
7