I have an interface
interface x {
A getValue();
}
and the implementation
class y implements x {
public B getValue() { return new B();}
}
B is a subclass of A. This works because of covariant overriding, I guess.
But if I rewrite the interface as
interface x{
<T extends A> T getValue();
}
I get a warning in the implementation that
Warning needs a unchecked cast to
conform to A.getValue()
What is the difference between 2 versions of the interface? I was thinking they are the same.
The second version of the interface is wrong. It says that the
getValuewill return any subclass you ask for – the return type will be inferred based on the expression on your left hand.So, if you obtain a reference to an
x(let’s call itobj), you can legally make the following call without compiler warnings:Which is probably incorrect in your example, because if you add another class
Cthat also extendsA, you can also legally make the call:This is because
Tis not a type variable belonging to the interface, only to the method itself.