Reputation: 277
I have a class that looks like this.
class SuperClass<T> {
public <K extends ClassB> K someMethod(T t) {
return null;
}
}
class ClassB {
}
class ClassA extends ClassB {
}
class ClassC {
}
public class Main extends SuperClass<ClassC>{
@Override
public ClassA someMethod(ClassC c) { //type safety warning in ClassA
return null;
}
}
From my understanding, the return type of someMethod()
can be any class that extends ClassB
or ClassB
itself. Clearly ClassA
is ClassB
. What seems to be the problem and why am I getting a type safety warning?
Upvotes: 3
Views: 58
Reputation: 70277
public <K extends ClassB> K someMethod(T t) {
return null;
}
You're making a guarantee to the callers here. You're telling them "no matter what subclass of SuperClass
we're working with, this method will return a value that can safely be treated as any subclass of ClassB
". Then your subclass Main
comes along and breaks that promise, by making a version that only returns ClassA
, which is a direct violation of the contract you've made. The generic extends
/ super
declarations are promises to the caller, not to the person extending the code.
Upvotes: 4