Monday, September 3, 2012

To Extend or to Implement

This is the most basic question that i never been able to understand until i made a program in which i started a  thread twice .

The answer that novice programmer give is
1) a Java class can have only one superclass. So if your thread class extends java.lang.Thread, it cannot inherit from any other classes. This limits how you can reuse your application logic.

correct !!
Now when same question is asked to an exp programmer then some more reason is expected  .
The reason is

2) Once a thread is  finished with its task ie: comes out of run method and cannot be restarted . Thread instance is subjected to garbage collection. So in order to resubmit the task again at some point then implementing interface is required. Also  the task can be submitted for a later point of execution .


From a design point of view, there should be a clean separation between how a task is identified and defined, between how it is executed. The former is the responsibility of a Runnable impl, and the latter is job of the Thread class.

No comments: