I know that implements Runnable
is preferred over extends Thread
in Java threads as it allows us to extend some other class if it is required. But if this is the case, does extends Thread
also have its own advantages over implements Runnable
and if so, what are these advantages?
When we extend Thread class, we can't extend any other class even we require and When we implement Runnable, we can save a space for our class to extend any other class in future or now.
OK, but you can't extend the Thread class without creating a Runnable because Thread is Runnable. The real choice is, do you extend the Thread class, or do you create a base Thread instance and give it a Runnable delegate.
Create a Thread by Extending a Thread Class This approach provides more flexibility in handling multiple threads created using available methods in Thread class.
They cannot make it final , however, because that would break backward compatibility. As far as practical reasons go, I think the only reason you may want to extend Thread rather than implement Runnable today would be to override its methods other than run() .
Because sometimes (almost never, but sometimes) you want to be able to change the basic behaviour of Thread
.
That's when you'll need to extend it.
You can change it by overriding a method from the Thread
class, you can't do it by implementing one from Runnable
.
In the last 20+ years since Java 1.0 was released, what is a considered a good design pattern has changed. However, Java is committed to backward compatibility which means old code which might use poor design patterns will still work.
One of my pet hates is StringBuffer
for which it was never a good idea to make it's method synchronized, was replaced more than tens years ago, but unfortunately developers are not prevented from using it today and even new developers use it, even though it was deprecated long before they started using Java.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With