Friday, May 3, 2024

Differences Between Extends Thread And Implements Runnable In Java :

There are two ways you can create the threads in java. One is by extending java.lang.Thread class and another one is by implementing java.lang.Runnable interface. we will see the differences between “Extends Thread” and “Implements Runnable” and what is the best option between these two to create the threads in java

Differences Between Extends Thread And Implements Runnable In Java :

1) Multiple Inheritance Limitation

As you know, Java doesn’t support multiple inheritance. A class in java can extend only one class. If you extend Thread class, then your class will not be able to extend any other class. This will limit your class to thread behavior. If you implement Runnable interface, then you will have an option for your class to extend any other class and inherit behaviors from other class also.

2) Overhead Of Additional Methods

If you extend Thread class, all methods of Thread class will be inheriting to your class which you may not need. This will cause additional overhead. You can remove this overhead by implementing Runnable interface.

3) Best Object Oriented Design Practice

In object oriented programming, extending a class means modifying or improving the existing class. If you are not improving the class, then it is not a good practice to extend it. So, implementing Runnable will be the best object oriented design practice.

4) Reusability

Implementing Runnable improves the reusability of your code. Because, Runnable contains only the task and you can use it wherever and whenever you want it.

No comments:

Post a Comment