I have problem to use generics in one of my class. These are my classes:
public interface InterE<PK> {}
public interface Inter2<O extends ClassO, P extends ClassP> {}
public class ClassU<O extends ClassO, P extends ClassP> implements InterE<Long> {}
public class ClassP {}
public class ClassO {}
public class Class1<PK, T extends InterE<PK>> {
public Class1 (Class<T> clazz) {}
}
public class Class2<O extends ClassO, P extends ClassP> extends Class1<Long, ClassU<O, P>> implements Inter2<O, P> {
public Class2 () {
//old constructor
//super(ClassU.class);
//new - here is problem
super(ClassU<O, P>.class);
}
}
If ClassU does not use generics, then old constructor in Class2 works fine, but I need to use generics in ClassU, so I have problem to call super constructor in Class2.
A class can implement multiple interfaces and many classes can implement the same interface. Final method can't be overridden. Thus, an abstract function can't be final.
This is not possible.
Constructing an Instance of a Generic TypeYou cannot create instances of it unless you specify real types for its generic type parameters. To do this at run time, using reflection, requires the MakeGenericType method.
Java does not support "multiple inheritance" (a class can only inherit from one superclass). However, it can be achieved with interfaces, because the class can implement multiple interfaces. Note: To implement multiple interfaces, separate them with a comma (see example below).
Short story: change Class1
constructor parameter type - from Class<T>
to Class<?>
.
Why?
Class1
only needs T
to extend InterE
. Class2
declares ClassU
to be this T
argument. Since ClassU
implements InterE
, everything is OK for Class1
.
Do you really need this <T>
information in Class1
constructor? I think no:
1) T
is already present in class declaration: Class1<PK, T extends InterE<PK>>
, you can use it inside the class to generify code and make it compile-time safe:
public class Class1<PK, T extends InterE<PK>> {
Map<PK, T> map = new HashMap<>(); // can still use T, compile-time safe
}
2) What can Class<T>
do, that Class<?>
can not do? - it can create newInstance()
safe and do some more stuff, but you most likely won't use this possibility. Use still can operate with T
, for example call T instance = (T) class.newInstance();
, so you will not have any insuperable limitations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With