public class Yikes {
public static void go(Long n) {
System.out.print("Long ");
}
public static void go(Short n) {
System.out.print("Short ");
}
public static void go(int n) {
System.out.print("int ");
}
public static void main(String[] args) {
short y = 6;
long z = 7;
go(y);
go(z);
}
}
This program is giving the output
int Long
I thought the output was
short Long
What is the reason for this?
The overload resolution section in the JLS explains why:
- 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.
This guarantees that any calls that were valid in the Java programming language before Java SE 5.0 are not considered ambiguous as the result of the introduction of variable arity methods, implicit boxing and/or unboxing. However, the declaration of a variable arity method (§8.4.1) can change the method chosen for a given method method invocation expression, because a variable arity method is treated as a fixed arity method in the first phase. For example, declaring
m(Object...)
in a class which already declaresm(Object)
causesm(Object)
to no longer be chosen for some invocation expressions (such asm(null))
, asm(Object[])
is more specific.
- The second phase (§15.12.2.3) performs overload resolution while allowing boxing and unboxing, but still precludes the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the third phase.
In the first phase, the compiler does not include the method go(Short n)
in its resolution. Instead, it deems go(int n)
to be an applicable method. This method is applicable because a short
is widening converted to an int
.
The compiler is preferring to convert a short
into an int
rather than box it into a Short
object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With