![](/img/trans.png)
[英]Why does the division of two BigDecimal numbers in Java throws the 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.