1 package cspuzzles; 2 3 public class Post004 { 4 private void overloadedMethod(Object o){ 5 System.out.println("Object o"); 6 } 7 8 private void overloadedMethod(Number n){ 9 System.out.println("Number n"); 10 } 11 12 private void overloadedMethod(Integer i){ 13 System.out.println("Integer i"); 14 } 15 16 public static void main(String[] args){ 17 Post004 p = new Post004(); 18 p.overloadedMethod(10); 19 p.overloadedMethod(10.0); 20 p.overloadedMethod("Hello"); 21 p.overloadedMethod(new Integer(10)); 22 p.overloadedMethod(new Byte("1")); 23 p.overloadedMethod(new Post004()); 24 } 25 }Hint
When Java does not find a direct match for a method, it applies widening and/or autoboxing to the parameters trying to find the more specific matching method.
With autoboxing, the compiler automatically wraps primitive values in an object. For example, a literal integer is wrapped in an Integer object.
In the case of widening, the compiler tries to find a wider type than the original type. For example: an int can be widened to a long and a String can be widened to a Object.
Answer
Yes, it compiles and it prints:
Integer i Number n Object o Integer i Number n Object oExplanation
Let's explain what happens for each of the calls:
- overloadedMethod(10): 10 is an integer literal and is boxed to an Integer.
- overloadedMethod(10.0): 10.0 is a floating-point literal. The compiler first applies boxing (i.e. from double to Double). Then, it widens Double to Number.
- overloadedMethod("Hello"): in this case, we are passing a String object which is widened to Object.
- overloadedMethod(new Integer(10)): this is a direct method match.
- overloadedMethod(new Byte("1")): Byte is widened to Number.
- overloadedMethod(new Post004()): after all an object Post004 inherits from Object, that explains the last line printed.
See you next puzzle!
No comments:
Post a Comment