rlbaker rlbaker - 6 months ago 21
Java Question

Return Parameterized type in Sublclasss

I have a class with a method that returns a List with that class as the parameter type. I am trying to extend that class, and then override the method that returns that List and have the List parameterized to the subclass. The return type of the subclass is incompatible with the return type of the superclass.

public interface GenericReturnTypeList {

public <T> List<T> getNames();
}

class FirstName implements GenericReturnTypeList{
String fName;

public List<FirstName> getNames(){
return null;
}
}

class FullName extends FirstName{
String lName;

public List<FullName> getNames(){

}
}


Is there a different way to accomplish the same thing? thanks

Answer

Using wildcards and casting the returned List is how I ended up getting it to work. Not sure if this is the best practice:

public interface GenericReturnTypeList{

    public List<?> getNames();
}

class FirstName implements GenericReturnTypeList{
    String fName;

    public List<?> getNames(){
        return null;
    }
}

class FullName extends FirstName{
    String lName;

    public List<?> getNames(){
        return null;
    }

}

class NameGetter {

    public static void main(String[] args){

        GenericReturnTypeList firstN = new FirstName();
        List<FirstName> firstNList = (List<FirstName>) firstN.getNames();

        GenericReturnTypeList fullN = new FullName();
        List<FullName> fnList = (List<FullName>)fullN.getNames();

    }

}