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
Object
if no explicit bound is specified.
So why instantiating a type
parameter is illegal?
Simple: because that T
could be anything.
Assume you have a Gen<Integer>
. Surprise: Integer does not have a default constructor. So how do you intend to do new Integer()
then?
The compiler can't know whether there is a default constructor for the thing that comes in as T
.
java.lang.Object
obviously has such a constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With