我偶然发现了以下片段:
public class ParamTest {
public static void printSum(int a, double b) {
System.out.println("In intDBL " + (a + b));
}
public static void printSum(long a, long b) {
System.out.println("In long " + (a + b));
}
public static void printSum(double a, long b) {
System.out.println("In doubleLONG " + (a + b));
}
public static void main(String[] args) {
printSum(1, 2);
}
}
这将导致编译错误:
错误:(15,9)java:对printSum的引用是不明确的,在ParamTest中的方法printSum(int,double)和在ParamTest中的方法printSum(long,long)都匹配
这是如何模棱两可的?因为第一个参数已经是一个int,所以在这种情况下不应该仅提升第二个参数吗?在这种情况下,不需要推广第一个参数,对吗?
如果我更新代码以添加另一个方法,则编译成功:
public static void printSum(int a, long b) {
System.out.println(String.format("%s, %s ", a, b));
}
让我扩大一下以澄清。下面的代码导致歧义:
public class ParamTest {
public static void printSum(int a, double b) {
System.out.println("In intDBL " + (a + b));
}
public static void printSum(long a, long b) {
System.out.println("In long " + (a + b));
}
public static void main(String[] args) {
printSum(1, 2);
}
}
然后,下面的代码也导致歧义:
public class ParamTest {
public static void printSum(int a, double b) {
System.out.println("In intDBL " + (a + b));
}
public static void printSum(double a, long b) {
System.out.println("In doubleLONG " + (a + b));
}
public static void main(String[] args) {
printSum(1, 2);
}
}
但是,这不会导致歧义:
public class ParamTest {
public static void printSum(int a, double b) {
System.out.println("In intDBL " + (a + b));
}
public static void printSum(long a, double b) {
System.out.println("In longDBL " + (a + b));
}
public static void main(String[] args) {
printSum(1, 2);
}
}
Error:(15, 9) java: reference to printSum is ambiguous both method printSum(int,double) in ParamTest and method printSum(long,long) in ParamTest match
-不是模棱两可的方法,而是方法的调用是模棱两可的。