Let’s have the following class hierarchy:
public class MyType {
}
public class MySuperclass<T extends MyType> {
protected Map<String, String> myMap = new TreeMap<String, String>();
protected String myMethod(String s) {
return myMap.get(s);
}
}
public class MySubclass extends MySuperclass {
@Override
protected String myMethod(String s) {
return myMap.get(s); // <-- compilation error
}
}
Why there is a compilation error in the overriden method of MySubclass?
The error message is “Type mismatch: cannot convert from Object to String”.
The interesting thing is that the compilation error dissapears if I define generics class type for MySuperclass in MySubclass definition:
public class MySubclass extends MySuperclass<MyType> {
@Override
protected String myMethod(String s) {
return myMap.get(s);
}
}
Can somebody explain this behavior? I would consider it to be a Java compiler bug.
I’m using jdk1.6.0_24.
It is not a bug. By extending
MySuperclassinstead ofMySuperclass<MyType>, you’re extending the raw typeMySuperclass, which means thatmyMapwill also be of typeMapinstead ofMap<String, String>.