Difficulty: Medium
Correct Answer: System.out.println(new Runnable() {public void run() { }});
Explanation:
Introduction / Context:This checks syntax for anonymous inner classes that implement an interface. For interfaces, you must provide implementations of all abstract methods in the anonymous body.
Given Data / Assumptions:
Concept / Approach:Anonymous inner class creation expressions both instantiate and define a subclass or an implementation on the spot. If the target type is an interface, the body must implement all abstract methods.
Step-by-Step Solution:
Option D uses new Runnable() { public void run() { } } which correctly implements run() and constructs an instance; passing it to println is fine.Option A omits run(); an anonymous class implementing Runnable without run() will not compile.Option B uses illegal syntax (method header in the parentheses).Option C misses parentheses after Runnable and has formatting issues; also invalid syntax.Verification / Alternative check:Assign the expression in D to a variable: Runnable r = new Runnable() { public void run() {} }; This compiles and constructs an anonymous class.
Why Other Options Are Wrong:They violate required syntax or omit the mandatory run() implementation.
Common Pitfalls:Forgetting parentheses after the type name and forgetting to implement abstract methods in the anonymous body.
Final Answer:System.out.println(new Runnable() {public void run() { }});
Discussion & Comments