If I have the following:
public interface Foo {
<T extends Foo> T getBlah();
}
public class Bar implements Foo {
public Bar getBlah() {
return this;
}
}
I get a warning in eclipse about the 'getBlah' implementation in class Bar:
- Type safety: The return type Bar for getBlah from the type Bar needs unchecked conversion to conform to T from the type
Foo
How can I fix this? And why am I getting the warning?
Thanks
You are overriding a method from your interface, so your implementation you should match the signature from your specification:
public class Bar {
@Override
public <T extends Foo> T getBlah() {
return this;
}
}
Now, if you were instead planning on creating a specifically parametized override of the entire implementation, then you need to specify the generic type as a part of the interface definition:
public interface Foo<T extends Foo<T>> {
T getBlah();
}
public class Bar implements Foo<Bar> {
@Override
public Bar getBlah() {
return this;
}
}
<T extends Foo> T getBlah();
means that a caller can request any type as T to be returned. So no matter what class the object is, I can request some other random subclass of Foo of my choosing to be returned. The only value that such a method could validly return is null
(unless it does unsafe casts), which is probably not what you want.
I am not sure what do you want to accomplish here but I think that returning Foo would be OK:
interface Foo {
public Foo getBlah();
}
as you are not using the generic type anywhere in the parameters.
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