Java Programming - Threads - Discussion

Discussion Forum : Threads - Pointing out the correct statements (Q.No. 2)
2.
Which two can be used to create a new Thread?
  1. Extend java.lang.Thread and override the run() method.
  2. Extend java.lang.Runnable and override the start() method.
  3. Implement java.lang.Thread and implement the run() method.
  4. Implement java.lang.Runnable and implement the run() method.
  5. Implement java.lang.Thread and implement the start() method.
1 and 2
2 and 3
1 and 4
3 and 4
Answer: Option
Explanation:

There are two ways of creating a thread; extend (sub-class) the Thread class and implement the Runnable interface. For both of these ways you must implement (override and not overload) the public void run() method.

(1) is correct - Extending the Thread class and overriding its run method is a valid procedure.

(4) is correct - You must implement interfaces, and runnable is an interface and you must also include the run method.

(2) is wrong - Runnable is an interface which implements not Extends. Gives the error: (No interface expected here)

(3) is wrong - You cannot implement java.lang.Thread (This is a Class). (Implements Thread, gives the error: Interface expected). Implements expects an interface.

(5) is wrong - You cannot implement java.lang.Thread (This is a class). You Extend classes, and Implement interfaces. (Implements Thread, gives the error: Interface expected)

Discussion:
2 comments Page 1 of 1.

Gaurav said:   7 years ago
<%@ page implements = "java.lang.Runnable" %> why its give error?

Please, someone help me.

Kavinda said:   1 decade ago
Good question and good explanation, Thank you so much.

Post your comments here:

Your comments will be displayed after verification.