• 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
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

Question Regarding Boxing

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

I am doing the free mock exams available and stumbled upon a question that I need clarification on. For the question below:

Question 9

public class Boxing9 {
public static void main(String[] args) {
int i = 10;
method(i);
}
static void method(Object o){
System.out.println("Object called");
}
static void method(Number n){
System.out.println("Number called");
}
}


What will be the output for the above program?
1)Object called
2)Number called
3)Compiler Error
4)Runtim Exception

Why is the answer Number called instead of Object called? Even the answer indicates that the integer will be boxed to an Integer then widen to an Object:

Answer

2)Number Called
Explanation: The int i was boxed to a Integer.The Integer reference was widened to an Object (since Integer extends Object).The method() method got an Number reference that actually refers to a Integer object.
 
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think that the explaination contradicts with the answer, though answer seems to be right, i.e. Number version of the method will be called. The reason is that int will be boxed to Integer and since there is no Integer version of the method, it has to widen and choose between the "Number" version and the "Object version" and since "Number" is the "most-specific" version of the overloaded method, it will be called.

You can refer What is a most-specific method? from ths SCJP FAQ of javaranch.

Hope this helps.
 
David Yu
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks for your reply,
 
I've been selected to go to the moon! All thanks to this tiny ad:
New web page for Paul's Rocket Mass Heaters movies
https://coderanch.com/t/785239/web-page-Paul-Rocket-Mass
reply
    Bookmark Topic Watch Topic
  • New Topic