Java Programming - Inner Classes - Discussion

Discussion :: Inner Classes - General Questions (Q.No.5)


Which 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() { }});

Answer: Option D


D is correct. It defines an anonymous inner class instance, which also means it creates an instance of that new anonymous class at the same time. The anonymous class is an implementer of the Runnable interface, so it must override the run() method of Runnable.

A is incorrect because it doesn't override the run() method, so it violates the rules of interface implementation.

B and C use incorrect syntax.

C Srinivas Mukund said: (Nov 29, 2013)  
Answer B can be tempting but it is wrong the reason given below.

If a class includes an interface but does not fully implement the methods defined by that interface, then that class must be declared as abstract.

Abb said: (Apr 23, 2014)  
How is b having correct syntax? A method definition passed as a parameter to a constructor? Which version of java is this?

Prem said: (Jul 5, 2017)  
How is [C]. Runnable r = new Runnable { public void run(){}}; wrong syntax?. Please explain.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.