Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone clarify covariant return types in Java(6)?

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?

like image 423
end-user Avatar asked Dec 17 '22 03:12

end-user


1 Answers

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.

like image 196
Ravi Bhatt Avatar answered Jan 02 '23 17:01

Ravi Bhatt