Monday, March 15, 2010

Java Overloaded

Hey! For this puzzle, I need to use a class hierarchy. Instead of coding a small hierarchy inside the example; I will use the hierarchy of primitive wrapper classes like Interger, Short, Long, Byte. These classes inherit from class Number, which in turn inherits from Object. Given said that, here is the puzzle, what does the following code print? Do you think it even compiles?
 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 o
Explanation

Let's explain what happens for each of the calls:
  1. overloadedMethod(10): 10 is an integer literal and is boxed to an Integer.
  2. 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.
  3. overloadedMethod("Hello"): in this case, we are passing a String object which is widened to Object.
  4. overloadedMethod(new Integer(10)): this is a direct method match.
  5. overloadedMethod(new Byte("1")): Byte is widened to Number.
  6. overloadedMethod(new Post004()): after all an object Post004 inherits from Object, that explains the last line printed.
Huh! Sometimes overloading can be trickier than it seems. Did you get all of them correct? Would you like another puzzle about overloading? Let's hear your opinions in the comments.

See you next puzzle!

No comments:

Post a Comment