aurelien.thiriet
aurelien.thiriet

Reputation: 31

Instantiation of a generic type?

I have those two classes as example :

public class AClass {
    public int i;
    public static int static_i;

    public AClass(int i) {
    }

    public void aMethod() {}

    public static void aStaticMethod() {}

    public static AClass getInstance(int i) {
            return new AClass(i);
    }
}

and

public class AnOtherClass<T extends AClass> {
    T aMember;

    public void method() {
        // Instanciation of T failed
        aMember = new T(0);

        // Instanciation via getInstance static method failed
        aMember = T.getInstance(0);

        // OK
        T.aStaticMethod();
        // OK
        aMember.aMethod();
    }
}
  1. Instantiation of T failed: "Cannot instantiate the type T"
  2. Instantiation via getInstance static method failed: "Type mismatch: cannot convert from AClass to T"
  3. Why not? I don't understand why you cannot do this.
  4. Why cannot convert AClass to T since T is subclass of AClass?

Upvotes: 2

Views: 592

Answers (1)

amit
amit

Reputation: 178421

You cannot instantiate a generic. Remember - you can create a AnOtherClass<MyAbstractClass> [where MyAbstractClass is an abstract class that extends AClass], what would happen when you try to instantiate it then?

However - there is no problems to invoke a method of an already existing class/instance.

You might need to pass T to method() and create an instance using reflection to workaround it if you still want to create an object, or use the factory design pattern.

Upvotes: 4

Related Questions