Restriction of types of inheritance returns (generics)

I struggle with generic behavior that’s a bit strange regarding the possibility of narrowing down 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 getServiceto ITreeService. Warning

Security type: ITreeService return type for getService () from type TreeServiceTest needs an raw conversion to match V from type AbstractServiceTest

Why does ITreeService not have a valid tapering type for getService?

EDIT: error modified before warning

+3
source share
2 answers

, :

public abstract class AbstractServiceTest<T extends AbstractIndex> {
    abstract IService<T> getService();
}

V, , .:-P

+5

AbstractServiceTest V T, :

public abstract class AbstractServiceTest<T extends AbstractIndex, V extends IService<T>> { 
    abstract V getService(); 
} 

public class TreeServiceTest extends AbstractServiceTest<TreeIndex, ITreeService> { 
    @Override 
    ITreeService getService() { 
        return null; 
    } 
}

public class AnotherTreeServiceTest extends AbstractServiceTest<TreeIndex, AnotherTreeService> { 
    @Override 
    AnotherTreeService getService() { 
        return null; 
    } 
}

EDIT: , V , :

public void setService(V service) { ... }
+3

Source: https://habr.com/ru/post/1730064/


All Articles