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

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

user978
1#
user978 Published in July 21, 2018, 6:11 am

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<Animal> animals). By all the rules of inheritance and polymorphism, I would assume that a List<Dog> is a List<Animal> and a List<Cat> is a List<Animal> - 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 subset of Animal by saying doSomething(List<? extends Animal> 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?

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.509972 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO