Why is it not possible to create an instance of type parameter?

Abhishek Keshri :

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?

GhostCat salutes Monica C. :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=72919&siteId=1