我知道以下程序会出现编译错误:
方法runThis(Integer)对于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");
}
}
Run Code Online (Sandbox Code Playgroud)
此外,当我按如下方式更改程序时,它会输出"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");
}
Run Code Online (Sandbox Code Playgroud)
传入时null,可以将其转换为任何引用类型.Java将尝试使用最具体的类型查找重载方法.
在你的第一个例子中,可能性是Object,Integer和ArithmeticException. Integer并且ArithmeticException都比具体而言Object,但两者都没有比另一个更具体,所以它是模棱两可的.
在第二个例子中,可能性是Object,Exception和ArithmeticException. Exception并且ArithmeticException更具体Object,但ArithmeticException也更具体Exception,因此歧义有利于解决ArithmeticException.
该null可以是任何Object(包括Integer).添加一个演员,
改变这个
runThis(null);
Run Code Online (Sandbox Code Playgroud)
至
runThis((Integer) null);
Run Code Online (Sandbox Code Playgroud)
要么
runThis((Object) null);
Run Code Online (Sandbox Code Playgroud)
并消除歧义.