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.