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