• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Problems with Lists

 
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Greenhorn
Posts: 3
Oracle Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
An interesting related question at Inheritance - Mock Question & Explanation on Dan Chisholm's website.

Regards,
Dan
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic