Can we override a start() method in Java?

JavaObject Oriented ProgrammingProgramming

Yes, we can override the start() method of a Thread class in Java. We must call the super.start() method to create a new thread and need to call run() method in that newly created thread. If we call the run() method directly from within our start() method, it can be executed in the actual thread as a normal method, not in a new thread.

Example

public class ThreadTest {
   public static void main(String[] args) {
      MyThread t = new MyThread();
      t.start();
   }
}
class MyThread extends Thread {
   @Override
   public void start() { // overriding the start() method
      System.out.println("Overriding a start() method");
      super.start();
   }
   @Override
   public void run() {
      System.out.println("run() method ");
   }
}

Output

Overriding a start() method
run() method
raja
Published on 27-Aug-2019 08:07:31
Advertisements