2015-10-05 81 views
0

當我運行下面的代碼時,它給出輸出「算術異常」。由於算術異常被檢查爲異常,所以它具有比未經檢查的異常更高的優先級。 但它如何區分對象和算術異常?異常,算術異常和對象

public class Solution { 


public static void a(Exception e) 
{ 
    System.out.println("Exception"); 

} 
public static void a(ArithmeticException ae) 
{ 
    System.out.println("ArithmeticException"); 
} 

public static void a(Object o) 
{ 
    System.out.println("Object"); 
} 

public static void main(String[] args) 
{ 
    a(null); 
} 

}

+1

下面的答案是正確的。你也應該注意到'ArithmeticException'不是一個檢查的異常。 –

+1

[方法重載和選擇最具體類型]的可能重複(http://stackoverflow.com/questions/9361639/method-overloading-and-choosing-the-most-specific-type) –

回答

4

當重載方法,最具體的方法將作爲選。根據你的情況選擇的順序是

Arithmetic Exception > Exception > Object 

Language specification最具體的方法選擇在運行時。

如果多個成員方法都可訪問並適用於方法調用,則需要選擇一個方法來爲運行時方法調度提供描述符。 Java編程語言使用選擇最具體方法的規則。

Arithmetic ExceptionExceptionObject

0

Java語言更具體的會選擇方法的情況下,最具體的匹配與通過繼承與彼此爭論超載更加具體。

我們將用一個例子

public static void main(String[] args) { 
     a(new Exception("some exception")); 
     a(new ArithmeticException("something went wrong with numbers.")); 
     a(new String("hello world")); 
     a(null); 
    } 

的輸出爲預期演示此行爲: enter image description here