aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Question Regarding Boxing Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Question Regarding Boxing" Watch "Question Regarding Boxing" New topic
Author

Question Regarding Boxing

David Yu
Greenhorn

Joined: Oct 28, 2006
Posts: 24
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

Joined: Jul 26, 2005
Posts: 41
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

Joined: Oct 28, 2006
Posts: 24
thanks for your reply,
 
Consider Paul's rocket mass heater.
 
subject: Question Regarding Boxing