• 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

Generics.....problem

 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
List <? super Integer> al = new ArrayList<Number>(); //line 1
al.add(12); //line 2
al.add(12+ 13); //line 3
for (Number no:al) //line 4
{
System.out.println(no);
}
14)What will be the possible result of the above program?
a) Error at Line 1
b) Error at Line 2
c) Error at Line 3
d) Error at Line 4
e) Compile and execute Sucuessfully


ANS:
d)Error.Because in the declaration we have specified any super type of Integer,But in for
each loop we are specifying Number,We cannot restrict whenever we are using
lowerbound.So accepatble thing in line 4 is for (Object no:al).

Can any1 give clarification on this......?
 
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
i think the answer is correct as the line1 itself is invalid. you cannot assign an object of base class to its child class.

casting: allowed only subclass to parent class, i.e. up the hierarchy
 
Sheriff
Posts: 13411
Firefox Browser VI Editor Redhat
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Debajit Paul,
Please QuoteYourSources when posting mock questions. If a valid source is not added to this question soon, it will need to be removed.
 
Ranch Hand
Posts: 100
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Raghavan Chockalingam:
i think the answer is correct as the line1 itself is invalid. you cannot assign an object of base class to its child class.

casting: allowed only subclass to parent class, i.e. up the hierarchy



yes generally. but in this case of generics it will accept only classes that are superclass of Integer i.e. Number
if it was declared as <? extends Integer> than you answer would be valid.
 
reply
    Bookmark Topic Watch Topic
  • New Topic