Reputation: 31
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();
}
}
Upvotes: 2
Views: 592
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