我试图了解JAVA中的重载是如何工作的,并试图掌握在JAVA中扩展,自动装箱和varargs情况下应用的各种重载规则。在以下情况下,我无法理解发生了什么:
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
方法say的第三次调用时遇到编译错误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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句