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-variant
is correct but usasge is not. List<SubChild>
is not the same as List<SuperChild>
Consider this, List<Animals>
is not the same as List<Dogs>
and things can go horribly wrong if that was allowed. A Dog
is an Animal
but if it was allowed to assign like below:
List<Dogs> dogs = new ArrayList<Dogs>();
List<Animals> animals = dogs; //not allowed.
then what happens when you add a cat to it?
animals.add(new Cat());
and
Dog dog = dogs.get(0); //fail
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With