Thursday, 19 March 2009

Method overloading in Java 1.5

This post discusses the behaviour of method overloading in Java 1.5.

Suppose you have a class, which has a method void print(Integer x) and you call print(5) then Autoboxing will come into play and print will be called.

Another case is, if you have a method void print(long x) and you call print(5) then the primitive integer 5 will be widened to long and method print will be called.

Now suppose you have overloaded print method in your class

public class OverLoaded
{
public static void print(Integer i)
{
System.out.println("Integer");
}
public static void print(long l)
{
System.out.println("long")
}
public static void main(String args[])
{
int i = 10;
print(i)
}
}

There can be two possible outputs:
If you think "Autoboxing" will be done, then "Ineger" would be printed.
If you think "Widening" will be done, then "long" would be printed

Since both the method exists, which one will be used? Autoboxing or Widening?
In such situtations compiler uses the following order of priority:
  • Widening
  • Autoboxing
  • Var-args
Next question is what if there is a combination of these operations required.
When there is a combination of the above operations exists, the compiler will perform BoxingAndWidening but it will not perform WideningAndBoxing.

Class WidenNBox
{
static void print(Long x)
{
System.out.println("This is from long");
}
public static void main(String args[])
{
byte b = 10;
print(10);
}
}

In the above case, Compiler needs to widen byte to long first and then it should be boxed to Long which is not allowed.

Now consider this class

Class BoxNWiden
{
static void print(Object x)
{
System.out.println("This is from Object");
}
public static void main(String args[])
{
byte b = 10;
print(10);
}
}

Here compiler would autobox it to Byte first and then it can be widened to an Object.

No comments:

 
Technology