Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

generics

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?

like image 875
Abhishek Keshri Avatar asked Dec 18 '22 21:12

Abhishek Keshri


1 Answers

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.

like image 79
GhostCat Avatar answered Apr 05 '23 23:04

GhostCat