0

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;
}
Michal Przysucha
  • 1,021
  • 11
  • 13
  • 3
    You should take a look here http://stackoverflow.com/questions/1292109/generics-get-and-put-rule – Pshemo Jun 02 '14 at 13:38
  • I closed your question as duplicate but if you think duplicate doesn't explain your problem and you will be able to explain which part it not explained I will reopen your question. – Pshemo Jun 02 '14 at 13:49
  • This from your link was about collections and a rule about puting and geting, but I think it is the same rule in Java, that prevents from sending an object that is super-type to a method argument which is typed by generics with wildcard extends (? extends super-type). – Michal Przysucha Jun 02 '14 at 15:52

0 Answers0