Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question Regarding Boxing

 
David Yu
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • 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.
 
Hamid Virani
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • 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
  • Quote
  • Report post to moderator
thanks for your reply,
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic