2

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?
Cajunluke
  • 3,103
  • 28
  • 28
  • http://stackoverflow.com/questions/2434041/instantiating-generics-type-in-java http://stackoverflow.com/questions/2116404/java-generics-why-this-wont-work http://stackoverflow.com/questions/1090458/instantiating-a-generic-class-in-java – Oleg Mikheev Feb 25 '12 at 15:03

1 Answers1

4

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.

amit
  • 175,853
  • 27
  • 231
  • 333
  • the comment about `MyAbstractClass` is irrelevant. you can equally pass `MyAbstractClass.class` as the class object in, and it will equally fail to create it – newacct Feb 25 '12 at 22:51