Java Programming - Inner Classes - Discussion

Discussion Forum : Inner Classes - General Questions (Q.No. 5)
5.
Which constructs an anonymous inner class instance?
Runnable r = new Runnable() { };
Runnable r = new Runnable(public void run() { });
Runnable r = new Runnable { public void run(){}};
System.out.println(new Runnable() {public void run() { }});
Answer: Option
Explanation:

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.

Discussion:
3 comments Page 1 of 1.

Prem said:   8 years ago
How is [C]. Runnable r = new Runnable { public void run(){}}; wrong syntax?. Please explain.

Abb said:   1 decade ago
How is b having correct syntax? A method definition passed as a parameter to a constructor? Which version of java is this?

C Srinivas Mukund said:   1 decade ago
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.

Post your comments here:

Your comments will be displayed after verification.