Abhishek Keshri
Abhishek Keshri

Reputation: 3244

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

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?

Upvotes: 4

Views: 334

Answers (2)

gil.fernandes
gil.fernandes

Reputation: 14621

It is illegal when the type is unknown during runtime. This is due to type erasure.

Yet if you give your method or constructor the information about the type by passing the class of the type, then you can instantiate an object of that type using reflection - as long as there is a suitable constructor.

For example this is possible:

import javax.swing.*;

public class Gen<T> {

    T ob;
    Gen(Class<T> tClass) throws IllegalAccessException, InstantiationException {
        ob = tClass.newInstance(); // legal if class has default constructor!!!
    }

    public T getOb() {
        return ob;
    }

    public static void main(String[] args) throws InstantiationException, IllegalAccessException {
        Gen<JFrame> genFrame = new Gen<>(JFrame.class);
        if((genFrame.getOb() == null)) {
            throw new IllegalStateException();
        }
        Gen<JPanel> genPanel = new Gen<>(JPanel.class);
        if(genPanel.getOb() == null) {
            throw new IllegalStateException();
        }
    }
}

Upvotes: 0

GhostCat
GhostCat

Reputation: 140525

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.

Upvotes: 11

Related Questions