簡體   English   中英

為什么沒有調用實現Runnable接口的類的構造函數?

[英]Why is the constructor of a class which implements Runnable Interface not called?

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

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();
    }
}

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

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

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

Constructor是一個特殊的方法,它沒有return type ,其名稱與類名相同,因此從方法名中刪除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();
    }
}

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

暫無
暫無

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

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