• 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

Generic

 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi

I am new to Java and the forum, and I will be taking SCJP 6 exam on 23 November. I am using the most wonderful and interesting technical KS&BB book, and currently I am working on generics as is one of the areas that I really need to improve on. I have two classes i.e. Circle and Shape, where Circle is subclass of Shape. I tried to add a Shape object to the list declared in the below method , but got an error. I just need to find out why Shape cannot be added as is the supertype of Circle? My understanding is that List can take anything that is a Circle or a supertype of Circle.


Your assistance in this regard will be highly appreciated.


 
Sheriff
Posts: 9708
43
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Michael, welcome to javaranch.

The method can accept List<? super Circle> which means the list can be of type Circle or a super type of Circle. Lets say I pass this method an ArrayList<Circle>, then how can the compiler allow you to add an instance of Shape (super class of circle) to the list??
 
Bartender
Posts: 6663
5
MyEclipse IDE Firefox Browser Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Welcome to JR Michael.

The difference comes from what can be added to the list against what can be passed to the method that declares the list. Ankit's example is a good one to ponder upon
 
Michael Monchu
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It's a pleasure Ankit,

I do understand it now, the confusion was around what the method can accept, and what can be added to the list declared. Thanks a lot for clarity.

Kind regards,
Michael
 
Would you turn that thing down? I'm controlling a mind here! Look ... look at the tiny ad ...
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic