2014-03-26 67 views
2

我嘗試使用實現Runnable接口的類的構造函數。但我很驚訝地發現它從未被稱爲。 run()方法被調用,但是,構造函數從未被調用過。我寫了一個簡單的示例代碼來顯示這種現象。任何人都可以解釋爲什麼會發生?爲什麼實現Runnable接口的類的構造函數未被調用?

public class MyRunner implements Runnable { 

    public void MyRunner() { 
     System.out.print("Hi I am in the constructor of MyRunner"); 
    } 

    @Override 
    public void run() { 
     System.out.println("I am in the Run method of MyRunner"); 
    } 

    public static void main(String[] args){ 
     System.out.println("The main thread has started"); 
     Thread t = new Thread(new MyRunner()); 
     t.start(); 
    } 
} 
+3

構造函數沒有返回類型。 – Daniel

+0

DO構造函數有返回類型嗎?它是一種方法。刪除「空白」,你就會知道 –

+0

哎呀!感謝那。那對我來說太天真了。 – arsingh1212

回答

8

更改public void MyRunner()public MyRunner()(無返回類型)。 public void MyRunner()不是構造函數,而是一種方法。構造函數聲明沒有返回類型。

2

你有一個默認的構造函數,因爲你沒有定義任何構造函數。而且,默認的構造函數在內部被調用。

構造函數不能有返回類型。在你的情況下,public void MyRunner() {}是一種方法。從你的移除構造函數簽名。

1

Constructor是一種沒有return type的特殊方法,其名稱與Class名稱相同,因此從方法名稱中刪除void使其成爲構造函數。

public class MyRunner implements Runnable { 

    public MyRunner() { 
     System.out.print("Hi I am in the constructor of MyRunner"); 
    } 

    @Override 
    public void run() { 
     System.out.println("I am in the Run method of MyRunner"); 
    } 

    public static void main(String[] args) { 
     System.out.println("The main thread has started"); 
     Thread t = new Thread(new MyRunner()); 
     t.start(); 
    } 
} 

這將工作,你的構造函數將被調用。

相關問題