Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Narrowing return types on inheritance (generics involved)

Tags:

java

generics

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

like image 718
JesperE Avatar asked Feb 27 '23 17:02

JesperE


1 Answers

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

like image 110
Chris Jester-Young Avatar answered Mar 05 '23 16:03

Chris Jester-Young