2013-10-08 38 views
9
public class Test1 { 

    public static void main(String[] args) { 
     Test1 test1 = new Test1(); 
     test1.testMethod(null); 
    } 

    public void testMethod(String s){ 
     System.out.println("Inside String Method");  
    } 

    public void testMethod(Object o){ 
     System.out.println("Inside Object Method"); 
    } 
} 

當我嘗試運行給定的代碼,我得到以下的輸出:重載方法如何工作?

內字符串的方法

任何人都可以解釋爲什麼與String類型參數的方法獲取調用?

+1

+1它看起來像超級簡單的問題,但使用null ...這真的很有趣... –

+2

可能重複[在方法重載中奇怪的Java空行爲](http://stackoverflow.com/questions/14789478/奇怪的java空行爲在方法重載) –

+0

@RohitJain這個問題已經是[this]的副本(http://stackoverflow.com/questions/1545501/which-overload-will-get-selected- for-null-in-java) – mariomario

回答

19

最特定的方法參數被選擇用於重載方法

在這種情況下,StringObject子類。因此String變得比Object更具體。因此打印Inside String method

JLS-15.12.2.5

如果不止一個成員方法既方便和適用於方法調用

直接,有必要選擇一個提供運行時方法調度描述符。 Java編程語言使用選擇最具體方法的規則。

由於BMT和LastFreeNickName已正確提示,(Object)null將導致重載的方法,Object類型的方法被調用。

+3

但是對於null,String和Object都處於同一級別,那麼String如何更具體? –

+5

完全正確!你可以嘗試傳遞(Object)null作爲參數,它會選擇另一種方法。 – LastFreeNickname

+3

只要遇到代碼中的字符串文字,編譯器就會用它的值創建一個String對象,在這種情況下,* Null *。 – iMBMT

0

添加到現有的答覆,我不確定這是否是因爲問題以來的新版本的Java版本,但是當我試圖用一個方法編譯代碼時使用整數作爲參數而不是對象,代碼仍然編譯。但是,使用null作爲參數的調用在運行時仍然調用String參數方法。

例如,

public void testMethod(int i){ 
    System.out.println("Inside int Method");  
} 

public void testMethod(String s){ 
    System.out.println("Inside String Method");  
} 

還是會給予輸出:

Inside String Method 

調用時爲:

test1.testMethod(null); 

造成這種情況的主要原因是因爲字符串不接受空的值和int不。所以null被分類爲一個String對象。

回到所問的問題,類型Object僅在創建新對象時纔會遇到。這是通過任一類型的鑄造null作爲一個目的是通過

test1.testMethod((Object) null); 

或使用任何類型的物件的原始數據類型進行如

test1.testMethod((Integer) null); 
    or 
test1.testMethod((Boolean) null); 

或者通過簡單地通過

創建一個新對象
test1.testMethod(new Test1()); 

應當指出的是,

test1.testMethod((String) null); 

將再次調用String方法,因爲這將創建一個String類型的對象。

此外,

test1.testMethod((int) null); 
    and 
test1.testMethod((boolean) null); 

會給出一個編譯時錯誤,因爲布爾和INT不接受null作爲有效值和INT!=整數和布爾!=布爾。 整型和布爾型轉換爲int和boolean類型的對象。