代码
public class TestOverload {
public TestOverload(int i){System.out.println("Int");}
public TestOverload(char... c){System.out.println("char");}
public static void main(String[] args) {
new TestOverload('a');
new TestOverload(65);
}
}
输出
Int
Int
这是预期的行为吗?如果是这样,那为什么?我期待:char,Int
注意:我使用的是 Java 8
最佳答案
当编译器确定选择哪个重载方法时,具有可变参数 (...
) 的方法的优先级最低。因此TestOverload(int i)
选择 TestOverload(char... c)
当您调用 TestOverload
与单个 char
参数'a'
, 因为 char
可以自动升级为int
.
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 declares m(Object) causes m(Object) to no longer be chosen for some invocation expressions (such as m(null)), as m(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. This ensures that a method is never chosen through variable arity method invocation if it is applicable through fixed arity method invocation.
The third phase (§15.12.2.4) allows overloading to be combined with variable arity methods, boxing, and unboxing.
编辑:
如果您希望强制编译器调用 TestOverload(char... c)
构造函数,你可以传递给构造函数调用一个char[]
:
new TestOverload (new char[] {'a'});
关于java - 为什么编译器更喜欢 char 的 int 重载而不是 varargs char 重载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32471499/