userimage

Is List<Dog> a subclass of List<Animal>? Why aren't Java's generics implicitly polymorphic?

I have three classes

class Animal{

}

class Dog extends Animal{

}

class Cat extends Animal{

}

which is nothing but  Dog,Cat are sub-classes of Animal class.

Now, If there is a method(like myMethod(List<Animal>)) which accepts List<Animal> as a parameter, why am I unable to send List<Dog> or List<Cat> as a parameter to that method?? Actually it must accept that parameter according to polymorphism right??



userimage

No, a List<Dog> is not a List<Animal>. Consider what you can do with a List<Animal> - you can add any animal to it... including a cat. Now, can you logically add a cat to a list of dogs? Absolutely not.

//Incorrect code 

List<Dog> dogs = new List<Dog>();

List<Animal> animals = dogs; // cannot cast

animals.add(new Cat());

Dog dog = dogs.get(0); // This should be safe, right? how can a dog hold cat object .. that's wrong

Now, you can't add a Cat to a List<? extends Animal> because you don't know it's a List<Cat>. 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<? super Animal> - 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<Object>.

Answer is