I think I’m asking about covariant return types. I have some generated code that I’m trying to extend and use. Let’s suppose I have the following two classes:
public class SuperParent
{
public List<SuperChild> getList()
{
return new ArrayList<SuperChild>();
}
}
public class SuperChild
{
}
Now, I want to derive new classes from these thusly:
public class SubParent extends SuperParent
{
public List<SubChild> getList()
{
return new ArrayList<SubChild>();
}
}
public class SubChild extends SuperChild
{
}
The problem is, apparently I can’t override the getList() method because the return type doesn’t match, despite both classes being extended in the same direction. Can someone explain?
Your understanding of
co-variantis correct but usasge is not.List<SubChild>is not the same asList<SuperChild>Consider this,
List<Animals>is not the same asList<Dogs>and things can go horribly wrong if that was allowed. ADogis anAnimalbut if it was allowed to assign like below:then what happens when you add a cat to it?
and
So its not allowed.
As sugested by many others, use
List<? extends SuperChild>as return type to solve your problem.EDIT
To your comment above, if you do not have control over super class, i am afraid, you can not do anything.