Win a copy of Cloud Native PatternsE this week in the Cloud forum
or Natural Language Processing in the AI/ML 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Knute Snortum
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Ron McLeod
  • Piet Souris
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Frits Walraven
  • Ganesh Patekar

Query on Generics

 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • 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: 23834
140
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
  • 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
  • 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.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!