aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Problems with Lists Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Problems with Lists" Watch "Problems with Lists" New topic
Author

Problems with Lists

micha koern
Greenhorn

Joined: Mar 25, 2011
Posts: 23
Hi,
i have got a strange problem with Lists.

Animal is a superclass of Dog- because of this i thought the following would be fine.
Why cant i do this:



Why can i do this:


Thanks for your help!

Micha
Gaurav. Sachdeva
Greenhorn

Joined: Mar 12, 2012
Posts: 3

public class MyClass {

public static void main(String[] args) {
List<? super Dog> l = new ArrayList<Animal>();
l.add(new Animal());
}
}

class Animal {}
class Dog extends Animal{}
class Dog2 extends Dog {}
class Dog3 extends Dog2 {}

Here you are NOT able to add Animal object as it is not sure what will be reference type. The reference type is ? super Dog, so it can be Dog also. So you cannot add Animal Object to a Dog as ANIMAL IS NOT A DOG.

When you change above all methods invocations to as follows:

l.add((Dog) new Animal());
l.add((Dog2) new Animal());

Here it will compile as you can are casting Animal to a Dog or Dog2 and these can be added even if the reference type is Dog or any of its super class.
ALSO THIS CODE WILL COMPILE BUT WILL THROW A CLASS CAST EXCEPTION AT RUNTIME.


OCPJP 6.0 Certified
micha koern
Greenhorn

Joined: Mar 25, 2011
Posts: 23
Thank you now i understand...

The reference type is ? super Dog, so it can be Dog also.


This helps a lot.

Thank you

-Micha
Dan Drillich
Ranch Hand

Joined: Jul 09, 2001
Posts: 1180
An interesting related question at Inheritance - Mock Question & Explanation on Dan Chisholm's website.

Regards,
Dan

William Butler Yeats: All life is a preparation for something that probably will never happen. Unless you make it happen.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Problems with Lists