我知道下面的程序会出现编译错误:
The method runThis(Integer) is ambiguous for the type Other
我不明白的是原因。
public class Other {
public static void main(String[] args) {
runThis(null);
}
private static void runThis(Integer integer){
System.out.println("Integer");
}
private static void runThis(Object object){
System.out.println("Object");
}
private static void runThis(ArithmeticException ae){
System.out.println("ArithmeticException");
}
}
此外,当我如下更改程序时,它会打印“ArithmeticException”。我也不知道是什么原因。谁能给我解释一下?
public class Other {
public static void main(String[] args) {
runThis(null);
}
private static void runThis(Exception exception){
System.out.println("Exception");
}
private static void runThis(Object object){
System.out.println("Object");
}
private static void runThis(ArithmeticException ae){
System.out.println("ArithmeticException");
}
最佳答案
当您传入 null
时,可以将其转换为任何引用类型。 Java 将尝试找到具有最具体类型的重载方法。
在您的第一个示例中,可能性是 Object
、Integer
和 ArithmeticException
。 Integer
和 ArithmeticException
都比 Object
更具体,但两者都不比另一个更具体,所以它是不明确的。
在您的第二个示例中,可能性是 Object
、Exception
和 ArithmeticException
。 Exception
和 ArithmeticException
都比 Object
更具体,但是 ArithmeticException
也比 Exception
,因此歧义得到解决,有利于 ArithmeticException
。
关于java - 调用重载方法时出现错误信息 "is ambiguous for the type Other",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26389263/