Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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();
    }
}
like image 890
arsingh1212 Avatar asked Dec 05 '22 07:12

arsingh1212


1 Answers

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.

like image 108
Jay Avatar answered May 11 '23 00:05

Jay