Inheritance with typed collections

W

Will Cheeder

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
 
S

Stefan Ram

Will Cheeder said:
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 );
 
E

Eric Sosman

Will said:
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)
 
P

Philipp

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/bcbd48d4566a7575


Phil
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,230
Latest member
LifeBoostCBD

Latest Threads

Top