I'm wrestling with a bit of weird generics behavior regarding being able to "narrow" return types when subclassing. I managed to reduce the problem to the following set of classes:
public class AbstractIndex {
}
public class TreeIndex extends AbstractIndex {
}
public interface IService<T extends AbstractIndex> {
}
public interface ITreeService extends IService<TreeIndex> {
}
public abstract class AbstractServiceTest<T extends AbstractIndex> {
abstract <V extends IService<T>> V getService();
}
public class TreeServiceTest extends AbstractServiceTest<TreeIndex> {
@Override
ITreeService getService() {
return null;
}
}
The problem is that Java warns when I try to narrow the return type of getService
to ITreeService
. The warning is
Type safety: The return type ITreeService for getService() from the type TreeServiceTest needs unchecked conversion to conform to V from the type AbstractServiceTest
Why is not ITreeService a valid narrowing type for getService
?
EDIT: changed error to warning
Because I think you meant to say this:
public abstract class AbstractServiceTest<T extends AbstractIndex> {
abstract IService<T> getService();
}
There's no purpose to making the separate V
type variable, other than adding constraints that your subclasses can't fulfil. :-P
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