【问题标题】:why does ambiguity not raised for ArithmeticException parameter method为什么 ArithmeticException 参数方法没有引发歧义
【发布时间】:2015-10-28 03:32:05
【问题描述】:

以下代码执行时没有任何歧义编译错误,输出为“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");
    } 
}

【问题讨论】:

标签: java oop exception core arithmeticexception


【解决方案1】:

在这种情况下,规则是match the most specific method。由于ArithmeticException extends Exception 和ArithmeticException extends Object,没有歧义:ArithmeticException 比其他任何一个都更具体。

如果你添加这个:

private static void testMetod(String string) {
    System.out.println("String");
}

你会得到一个编译错误,因为ArithmeticException extends String 不是真的,反之亦然:没有一个最具体的参数类。

在这一点上说所有这些都发生在编译时可能很重要。一旦解析了目标方法并编译了代码,对重载方法的调用就像对任何其他方法的调用一样。这与方法覆盖形成对比。

【讨论】:

    猜你喜欢
    • 2015-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-17
    • 1970-01-01
    • 1970-01-01
    • 2018-07-19
    • 1970-01-01
    相关资源
    最近更新 更多