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.
If we can't eliminate the “unchecked cast” warning and we're sure that the code provoking the warning is typesafe, we can suppress the warning using the SuppressWarnings(“unchecked”) annotation. When we use the @SuppressWarning(“unchecked”) annotation, we should always put it on the smallest scope possible.
An unchecked warning tells a programmer that a cast may cause a program to throw an exception somewhere else. Suppressing the warning with @SuppressWarnings("unchecked") tells the compiler that the programmer believes the code to be safe and won't cause unexpected exceptions.
1 Answer. Show activity on this post. Adding @Suppress("UNCHECKED_CAST") (also possible through IDEA's Alt + Enter menu) to any of statement, function, class and file should help.
The second version of the interface is wrong. It says that the getValue
will 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 it obj
), you can legally make the following call without compiler warnings:
x obj = ...;
B b = obj.getValue();
Which is probably incorrect in your example, because if you add another class C
that also extends A
, you can also legally make the call:
C c = obj.getValue();
This is because T
is not a type variable belonging to the interface, only to the method itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With