I have a problem with generics.
I have one SuperType and two SubTypes. The class structure is following:
class SuperType {}
class FirstSubType extends SuperType {}
class SecondSubType extends SuperType {}
Then I create TypedClass with one method:
abstract class TypedClass<T extends SuperType> {
protected abstract String getStatus(T o);
}
I try to use it as an anonymous classes: one for FisrtSubType and one for SecondSubType:
new TypedClass<FirstSubType>() {
@Override
protected String getStatus(FirstSubType o) {
return "FirstSubType";
}
};
and
new TypedClass<SecondSubType>() {
@Override
protected String getStatus(SecondSubType o) {
return "SecondSubType";
}
};
And I try to keep theese objects in variable with type:
TypedClass<? extends SuperType> typedClass;
When I get an object of SuperType and try to call getStatus with that object as an argument I get an error: ? extends SuperType cannot be applied to SuperType.
The code is following:
private void go(SuperType superTypeObj, String strT) {
TypedClass<? extends SuperType> typedClass = getTypedClass(strT);
String status = typedClass.getStatus(superTypeObj);
System.out.println(status);
}
The code of above method brokes in second line (calling getStatus with superTypeObj as an argument).
The method getTypedClass(String strT)
returns TypedClass<? extends SuperType>
and creates TypedClass<FirstSubType>
or TypedClass<SecondSubType>
depending on String parameter (strT):
private TypedClass<? extends SuperType> getTypedClass(String strType) {
TypedClass<? extends SuperType> res = null;
if ("FirstSubType".equals(strType)) {
res = new TypedClass<FirstSubType>() {
@Override
protected String getStatus(FirstSubType o) {
return "FirstSubType";
}
};
} else {
res = new TypedClass<SecondSubType>() {
@Override
protected String getStatus(SecondSubType o) {
return "SecondSubType";
}
};
}
return res;
}