Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any simple way to explain why I cannot do List<Animal> animals = new ArrayList<Dog>()? [duplicate]

Tags:

I know why one shouldn't do that. But is there way to explain to a layman why this is not possible. You can explain this to a layman easily : Animal animal = new Dog();. A dog is a kind of animal but a list of dogs is not a list of animals.

like image 841
fastcodejava Avatar asked Feb 27 '10 09:02

fastcodejava


1 Answers

Imagine you create a list of Dogs. You then declare this as List<Animal> and hand it to a colleague. He, not unreasonably, believes he can put a Cat in it.

He then gives it back to you, and you now have a list of Dogs, with a Cat in the middle of it. Chaos ensues.

It's important to note that this restriction is there due to the mutability of the list. In Scala (for example), you can declare that a list of Dogs is a list of Animals. That's because Scala lists are (by default) immutable, and so adding a Cat to a list of Dogs would give you a new list of Animals.

like image 133
Brian Agnew Avatar answered Nov 07 '22 23:11

Brian Agnew