Creating a Thread with a Runnable target — which class definitions compile for "new Thread(target)"?\n\nGiven:\nRunnable target = new MyRunnable();\nThread myThread = new Thread(target);\n\nChoose the valid implementation for MyRunnable.

Difficulty: Easy

Correct Answer: public class MyRunnable implements Runnable{public void run(){}}

Explanation:


Introduction / Context:
To construct a Thread with a Runnable target, the argument must implement the java.lang.Runnable interface. The interface declares one method: public void run().



Given Data / Assumptions:

  • The Thread constructor used is Thread(Runnable target).
  • We are deciding which candidate MyRunnable compiles and can be passed to that constructor.


Concept / Approach:
A class can implement an interface, not extend it. When implementing Runnable, the run method must be declared public to satisfy the interface’s public abstract signature. A package-private run() fails to implement the interface method due to reduced visibility.



Step-by-Step Solution:

Option A: "extends Runnable" is invalid; Runnable is an interface, not a class.Option B: Extending Object alone does not implement Runnable; cannot be used as the Thread target.Option C: Correct. Implements Runnable and provides public void run().Option D: Incorrect visibility; method must be public to implement Runnable.run().


Verification / Alternative check:
Compile Option C and pass new MyRunnable() into new Thread(target); code compiles and runs.



Why Other Options Are Wrong:

  • They either misuse inheritance for an interface or fail the visibility requirement.


Common Pitfalls:
Forgetting that interface methods are implicitly public and must be implemented with public visibility.



Final Answer:
public class MyRunnable implements Runnable{public void run(){}}

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion