Here is what I know about overload resolution in java:
The process of compiler trying to resolve the method call from given overloaded method definitions is called overload resolution. If the compiler can not find the exact match it looks for the closest match by using upcasts only (downcasts are never done).
Here is a class:
public class MyTest {
public static void main(String[] args) {
MyTest test = new MyTest();
Integer i = 9;
test.TestOverLoad(i);
}
void TestOverLoad(int a){
System.out.println(8);
}
void TestOverLoad(Object a){
System.out.println(10);
}
}
As expected the output is 10.
However if I change the class definition slightly and change the second overloaded method.
public class MyTest {
public static void main(String[] args) {
MyTest test = new MyTest();
Integer i = 9;
test.TestOverLoad(i);
}
void TestOverLoad(int a){
System.out.println(8);
}
void TestOverLoad(String a){
System.out.println(10);
}
}
The output is 8.
Here I am confused. If downcasting was never to be used, then why did 8 get printed at all? Why did compiler pick up the TestOverLoad
method which takes int
as an argument which is a downcast from Integer
to int
?
The compiler will consider not a downcast, but an unboxing conversion for overload resolution. Here, the Integer
i
will be unboxed to an int
successfully. The String
method isn't considered because an Integer
cannot be widened to a String
. The only possible overload is the one that considers unboxing, so 8
is printed.
The reason that the first code's output is 10
is that the compiler will consider a widening reference conversion (Integer
to Object
) over an unboxing conversion.
Section 15.12.2 of the JLS, when considering which methods are applicable, states:
- The first phase (§15.12.2.2) performs overload resolution without permitting boxing or unboxing conversion, or the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the second phase.
- The second phase (§15.12.2.3) performs overload resolution while allowing boxing and unboxing [...]