April 8, 2024

Can we Override start() Method in Java

In some Java interviews there is a question asked can we override start() method in Java. Since this is something you will hardly need to do, so some people do get confused that is it actually possible to override start() method of Thread class or not. Also there is a follow up question will your overridden start() method actually execute the thread and call the run() method or not.

Overriding start method in Java

Yes it is possible to override start() method of the Thread class in Java. Though it is hardly required to do that except for some rare scenarios where you do need some logic to be executed before calling the run() method.

From your overridden start() method ensure that you call super.start() method as Thread class’ start() method is a native method and has the logic to communicate with the OS to schedule the thread to run. Failing to call super.start() will mean run() method won’t be called.

Overriding start method example code

public class MyThread extends Thread {
  @Override
  public void start(){
    System.out.println("In overridden start method");
    // calling parent class start method
    super.start();
  }

  @Override
  public void run() {
    System.out.println("In run method " + "Thread Name - " 
        + Thread.currentThread().getName());
  }

  public static void main(String[] args) {
    Thread t1 = new MyThread();
    t1.start();
  }
}
Output
In overridden start method
In run method Thread Name - Thread-0

That's all for the topic Can we Override start() Method in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment