• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problems with Lists

 
micha koern
Greenhorn
Posts: 23
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3
Java Oracle Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
micha koern
Greenhorn
Posts: 23
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1183
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
An interesting related question at Inheritance - Mock Question & Explanation on Dan Chisholm's website.

Regards,
Dan
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic