Win a copy of Murach's MySQL this week in the JDBC and Relational Databases forum!
  • 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

Query on Generics

 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi ,

This question is taken from www.javabeat.net


My doubt here is, we declared the return type as List<? super Integer> i.e it can accept Integer and any super classes of Integer

but in for(Number n:l) , Number is a super class of Integer, but why do we still get compiler error. Please clarify on this.
 
author
Posts: 23949
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

My doubt here is, we declared the return type as List<? super Integer> i.e it can accept Integer and any super classes of Integer

but in for(Number n:l) , Number is a super class of Integer, but why do we still get compiler error. Please clarify on this.



Well, that is the problem. The variable can be a list of Integer or any of its super classes. The compiler doesn't know what type it is.

And since that type can be an Object type, it can't allow it to be used in an operation that requires a Number, as it may not be a Number.

Henry
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Henry,

Please acknowledge me, If I'm echoing back what you have said? Since the return type is not specific, compiler can't assume that the return type would be only Number and hence errors out. Because return type could be even Object and that can't be referenced using Number.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic