In Java, creating an instance of type parameter is illegal, so the following code won't work:
class Gen<T> {
T ob;
Gen() {
ob = new T(); // Illegal!!!
}
}
The reason behind this is:
T does not exist at runtime, then how would the compiler know what type of object to create.
But what I fail to understand is, using erasure the following code will translate to:
class Gen {
Object ob;
Gen() {
ob = new Object(); // Perfectly Fine!!!
}
}
Because:
When your Java code is compiled, all generic type information is removed (erased). This means replacing type parameters with their bound type, which is
Objectif no explicit bound is specified.
So why instantiating a type parameter is illegal?