Hi,
If I have a class, Cat, which extends Animal, why can't I pass a
List<Cat> to a method that takes a List<Animal>? This should work,
since Cat inherits from Animal. Why doesn't inheritance include typed
collections? This seems like a gap in Java's polymorphism.
Thanks,
Andrew
Stefan Ram - 20 Jun 2007 23:30 GMT
>why can't I pass a List<Cat> to a method that takes a List<Animal>?
Because an list of animals can do more than a list
of cats (i.e., accept an animal), so that a list
of cats is not a subtype of it.
Assume,
java.util.List<Cat> catList = new java.util.ArrayList<Cat>();
Now assume, the following assignement would be allowed:
java.util.List<animal> animalList = catList;
Then one could add an animal to this »animalList«:
animalList.add( new animal(){} );
However, this would break the type of »catList«, because
the following call to the get-Operation of the catList now
will not return a cat, because we have been allowed to add
an animal above:
Cat cat = catList.get( 0 );
Eric Sosman - 21 Jun 2007 02:45 GMT
> Hi,
>
> If I have a class, Cat, which extends Animal, why can't I pass a
> List<Cat> to a method that takes a List<Animal>? This should work,
> since Cat inherits from Animal. Why doesn't inheritance include typed
> collections? This seems like a gap in Java's polymorphism.
Because your method might add a Dog to the List<Animal>.
Since it's actually a List<Cat>, you would then have trouble.
The Hydrogen Dog and the Cobalt Cat
Side by side in the armory sat.
Nobody talked about fusion or fission;
Everyone spoke of their peacetime mission
'Til somebody came in and opened the door ...
There they were in a neutron fog:
The Codrogen Cat and the Hybalt Dog.
They mushroomed up with a terrible roar,
And nobody never was there, no more.
-- "A Space Child's Mother Goose"
Winsor & Parry
(from possibly inaccurate memory)

Signature
Eric Sosman
esosman@acm-dot-org.invalid
Philipp - 21 Jun 2007 06:54 GMT
Will Cheeder a écrit :
> Hi,
>
> If I have a class, Cat, which extends Animal, why can't I pass a
> List<Cat> to a method that takes a List<Animal>? This should work,
> since Cat inherits from Animal. Why doesn't inheritance include typed
> collections? This seems like a gap in Java's polymorphism.
Make the method parameter signature be
public void myMethod(List<? extends Animal> myAnimalList)
and it will work.
See also for this thread for links to tutorials I found useful
http://groups.google.com/group/comp.lang.java.programmer/browse_thread/thread/bc
bd48d4566a7575
Phil