Java Programming - Threads - Discussion

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.

[A]. 1 and 2
[B]. 2 and 3
[C]. 1 and 4
[D]. 3 and 4

Answer: Option C

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)


Kavinda said: (May 8, 2014)  
Good question and good explanation, Thank you so much.

Gaurav said: (Feb 25, 2018)  
<%@ page implements = "java.lang.Runnable" %> why its give error?

Please, someone help me.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.