Win a copy of Micro Frontends in Action this week in the Server-Side JavaScript and NodeJS 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
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

Generics.....problem

 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • 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
  • 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
  • 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
  • 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.
 
Can you smell this for me? I think this tiny ad smells like blueberry pie!
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic