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);
}
}
这个程序给出了输出
int Long
我以为输出是
short Long
这是什么原因?
最佳答案
overload resolution section in the JLS解释原因:
- 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.
在第一阶段,编译器在其解析中不包含方法go(Short n)
。相反,它认为 go(int n)
是一种适用的方法。此方法适用,因为 short
正在加宽转换为 int
。
关于java - 为什么 Short 方法调用整数方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32569884/