下面的代码执行时没有任何歧义的编译错误,输出为
ArithmeticException
。你能帮我知道原因吗?
class Test {
public static void main(String[] args) throws UnknownHostException, IOException {
testMetod(null);
}
// Overloaded method of parameter type Object
private static void testMetod(Object object) {
System.out.println("Object");
}
// Overloaded method of parameter type Exception
private static void testMetod(Exception e) {
System.out.println("Exception");
}
// Overloaded method of parameter type ArithmeticException
private static void testMetod(ArithmeticException ae) {
System.out.println("ArithmeticException");
}
}
在这种情况下,规则是“匹配最具体的方法”。由于 ArithmeticException extends Exception
和
ArithmeticException extends Object
,没有歧义:ArithmeticException
比其他任何一个都更具体。如果你添加这个:
private static void testMetod(String string) {
System.out.println("String");
}
您将收到编译错误,因为
ArithmeticException extends String
都不是 true,反之亦然:不存在单个最具体的参数类。
此时可能很重要的一点是,所有这些都发生在编译时。一旦目标方法被解析并且代码被编译,对“重载”方法的调用就像对任何其他方法的调用一样。这与方法
覆盖形成对比。