我试图了解 JAVA 中的重载是如何工作的,并试图掌握在 JAVA 中加宽、自动装箱和可变参数的情况下应用的各种重载规则。我无法理解以下场景中发生的情况:
package package1;
public class JustAClass {
public static void add(int a, long b) {
System.out.println("all primitives");
}
//public static void add(Integer a, long b) {
// System.out.println("Wraper int, primitive long");
//}
public static void add(int a, Long b) {
System.out.println("Primitive int, Wrapper long");
}
public static void add(Integer a, Long b){
System.out.println("All wrapper");
}
public static void main(String[] args) {
int a = 10;
Integer b = 10;
long c = 9;
Long d = 9l;
add(a,c);
add(a,d);
add(b,c);
add(b,d);
}
}
此时,我在第三次调用时出现编译错误add
方法说The method is ambiguous for the type Error
。
为什么会这样呢?确定哪种方法调用有效的规则是什么?下面的案例到底发生了什么?
我觉得fourth
重载的 add 方法应该可以工作。请帮助我理解这背后的概念。
方法重载解析分为 3 个阶段。第一阶段不进行自动装箱/拆箱,这意味着需要对传递的参数进行装箱/拆箱才能匹配其中一个重载版本的方法add
仅当未找到不需要装箱/拆箱的匹配时才会考虑。这就是为什么您的 3 个具有单一精确匹配的调用能够起作用。关于add(b,c);
,请参阅下面为什么它不明确。
add(a,c); // exact match to add(int a, long b)
add(a,d); // exact match to add(int a, Long b)
add(b,c); // there is no exact match, so at least one of the passed parameters must
// be boxed or unboxed. However, by unboxing b to int or boxing
// c to Long, each of the three add methods can match, and the
// compiler doesn't know which one to prefer
add(b,d); // exact match to add(Integer a, Long b)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)