InterviewSolution
Saved Bookmarks
| 1. |
Implement Runnable vs Extend Thread in Java |
|
Answer» We have the ability to define a Thread in two ways:
By the first technique, the Thread class is extended. Since Java doesn’t support MULTIPLE inheritance, we can’t extend any other class. This is a shortcoming as the benefits of inheritance can’t be completely exploited. By the second technique, the Runnable interface is implemented. We can extend any other class and use the ADVANTAGES of inheritance completely. Let us see a program where we extend the Thread class: public class Example EXTENDS Thread // any other class can’t be extended { public void run() { System.out.println("Thread running"); } public static void main(STRING[] args) { Example obj = new Example(); obj.start(); // it CALLS the run() method System.out.println("Thread starting"); } }The output is as follows: $javac Example.java $java Example Thread starting Thread runningLet us now see the implementation of the Runnable interface class Parent { public static void method() { System.out.println("This is an extended class"); } } // since Runnable is a interface, class Example can extend class Parent public class Example extends Parent implements Runnable { public void run() { System.out.println("Thread running"); } public static void main(String[] args) { Example obj = new Example(); obj.method(); Thread t = new Thread(obj); // creating a new thread t t.start(); // calls the run() method System.out.println("Thread starting"); } }The output is as follows: $javac Example.java $java Example This is an extended class Thread starting Thread running |
|