簡體   English   中英

為什么沒有為ArithmeticException參數方法引發歧義

[英]why does ambiguity not raised for ArithmeticException parameter method

下面的代碼執行時沒有任何歧義的編譯錯誤,輸出是“ 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都沒有, ArithmeticException extends String :沒有一個最具體的參數類。

在這一點上說這一切都發生在編譯時可能很重要。 一旦解決了目標方法並編譯了代碼,對重載方法的調用就像調用任何其他方法一樣。 這與方法重寫形成對比。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM