File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Why list of animals is not accepting list dogs or cats? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Why list of animals is not accepting list dogs or cats?" Watch "Why list of animals is not accepting list dogs or cats?" New topic
Author

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

chaitanya karthikk
Ranch Hand

Joined: Sep 15, 2009
Posts: 806

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.


Love all, trust a few, do wrong to none.
Jelle Klap
Bartender

Joined: Mar 10, 2008
Posts: 1763
    
    7

You need a bounded type parameter to make this work (also see this).


Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4391
    
    8

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.

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why list of animals is not accepting list dogs or cats?