This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why list of animals is not accepting list dogs or cats?

 
chaitanya karthikk
Ranch Hand
Posts: 806
Java MySQL Database Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all, I tried to do thisI am getting the following errorDog is extending Animal. Can anyone explain me why I am getting this error?

Thank you all in advance. Good day.
 
Jelle Klap
Bartender
Posts: 1951
7
Eclipse IDE Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You need a bounded type parameter to make this work (also see this).

 
Matthew Brown
Bartender
Posts: 4549
8
Java Netbeans IDE Scala
  • 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just because a Dog is-an Animal, it doesn't mean that a List<Dog> is-a List<Animal>. And the following example shows why. The point of generics is to give you type safety - the compiler will only allow things it knows will work. So what about the following code?


If this code is allowed, then the result is that the List<Dog> referenced by dogs contains a Cat! We've broken the type safety. So one of the lines must be faulty. Nothing wrong with line 1. Line 3 is just adding a Cat to a List<Animal> as far as the compiler is concerned (the compiler only looks at the reference type of the variables), and that should be fine. So line 2 caused the problem. That's why the compiler won't allow it.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic