HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaCritical

Is List<Dog> a subclass of List<Animal>? Why are Java generics not implicitly polymorphic?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
javaaregenericswhypolymorphicimplicitlyanimalsubclasslistdog

Problem

I'm a bit confused about how Java generics handle inheritance / polymorphism.

Assume the following hierarchy -

Animal (Parent)

Dog - Cat (Children)

So suppose I have a method doSomething(List animals). By all the rules of inheritance and polymorphism, I would assume that a List is a List and a List is a List - and so either one could be passed to this method. Not so. If I want to achieve this behavior, I have to explicitly tell the method to accept a list of any subclass of Animal by saying doSomething(List animals).

I understand that this is Java's behavior. My question is why? Why is polymorphism generally implicit, but when it comes to generics it must be specified?

Solution

No, a List is not a List. Consider what you can do with a List - you can add any animal to it... including a cat. Now, can you logically add a cat to a litter of puppies? Absolutely not.

// Illegal code - because otherwise life would be Bad
List dogs = new ArrayList(); // ArrayList implements List
List animals = dogs; // Awooga awooga
animals.add(new Cat());
Dog dog = dogs.get(0); // This should be safe, right?


Suddenly you have a very confused cat.

Now, you can't add a Cat to a List because you don't know it's a List. You can retrieve a value and know that it will be an Animal, but you can't add arbitrary animals. The reverse is true for List - in that case you can add an Animal to it safely, but you don't know anything about what might be retrieved from it, because it could be a List.

Code Snippets

// Illegal code - because otherwise life would be Bad
List<Dog> dogs = new ArrayList<Dog>(); // ArrayList implements List
List<Animal> animals = dogs; // Awooga awooga
animals.add(new Cat());
Dog dog = dogs.get(0); // This should be safe, right?

Context

Stack Overflow Q#2745265, score: 1070

Revisions (0)

No revisions yet.