Which of the following correctly constructs an anonymous inner class instance?
2025
Which of the following correctly constructs an anonymous inner class instance?
- A.
Runnable r = new Runnable() { };
- B.
Runnable r = new Runnable(public void run() { });
- C.
Runnable r = new Runnable { public void run(){}};
- D.
System.out.println(new Runnable() {public void run() { }});
Attempted by 7 students.
Show answer & explanation
Correct answer: D
To instantiate an anonymous class that implements an interface in Java, the syntax is new InterfaceName() { ... } — the interface name is immediately followed by parentheses (as in a constructor call), and the braces that follow must define a class body that overrides every abstract method the interface declares. For Runnable, that means overriding void run(). The resulting expression is itself a value of the interface type, so it can be used wherever that type is expected — assigned to a variable, passed as a method argument, and so on.
Applying this rule to the constructs above: the valid one places new Runnable() { public void run() { } } — parentheses immediately after Runnable, followed by a body that overrides run() — directly inside a println(...) call. Because that expression is syntactically self-contained and valid on its own, it can legally appear as an argument to println, which simply accepts an Object.
One construct leaves the anonymous class body empty, so run() is never overridden — the interface's abstract method requirement is left unsatisfied.
Another construct writes the method declaration inside the parentheses passed to new Runnable(...), instead of in a following class body — a method cannot be declared inside a constructor's argument list.
A third construct drops the parentheses that must directly follow the interface name, so the expression is not a valid anonymous-class instantiation at all.
Only the construct that pairs the parentheses immediately after the interface name with a body overriding run() is syntactically valid and satisfies the interface contract — that is the correct construct.