简体   繁体   中英

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

I tried using the constructor of a class which implements Runnable Interface. But I was surprised to see it was never called. The run() method was called, however, the constructor was never called. I have written a simple sample code to show the phenomenon. Can anyone explain why this is happening?

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

Change public void MyRunner() to public MyRunner() (no return type). public void MyRunner() is not a constructor, it's a method. Constructor declarations don't have a return type.

You have a default Constructor there, since you don't define any constructor. And, the default Constructor was called internally.

A Constructor can't have return type. In your case, public void MyRunner() {} is a method. remove void from you Constructor signature.

Constructor is a special method which does not have return type and its name is same as Class name so remove void from method name to make it constructor.

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

This will work and your constructor will be called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM