gpt4 book ai didi

java - 编译时错误: ambiguous on calling overloaded method. 为什么?

转载 作者:行者123 更新时间:2023-12-02 11:22:31 24 4
gpt4 key购买 nike

对于下面的代码,为什么会出现此编译时错误:

方法 overridedMethod(IOException) 对于类型 Test 来说不明确。

public class Test {

public static void main(String[] args) {
Test test = new Test();
test.overloadedMethod(null);

}

void overloadedMethod(IOException e) {
System.out.println("1");
}

void overloadedMethod(FileNotFoundException e) {
System.out.println("2");
}

void overloadedMethod(Exception e) {
System.out.println("3");
}

void overloadedMethod(ArithmeticException e) {
System.out.println("4");
}

}

最佳答案

FileNotFoundExceptionArithmeticException 在 java 对象层次结构中都处于同一级别。编译器困惑于选择最具体的方法,因为这两种方法都有资格调用。

如果存在多个对象层次结构,即使编译器也无法选择最具体的方法。因此,删除 FileNotFoundExceptionArithmeticException 都无法解决问题。

来自JLS 15.12.2.5

If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.

The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error.

关于java - 编译时错误: ambiguous on calling overloaded method. 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23739334/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com