It's not a secret anymore!*
The moose likes Beginning Java and the fly likes Anonymous classes Query Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Anonymous classes Query" Watch "Anonymous classes Query" New topic
Author

Anonymous classes Query

Pavan Kumar Dittakavi
Ranch Hand

Joined: Feb 12, 2011
Posts: 104

Hi All,

I have a small query. I am aware of this concept of Anonymous classes but, how is the following piece of code valid?...Aren't we creating an instance of runnable instance? An we cant instantiate an interface..so how is this allowed..please explain.




Thanks,
Pavan.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19651
    
  18

You are not creating an instance of Runnable, you are creating an instance of the anonymous class that implements Runnable.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

And just to make the syntactical difference clear:



The curly braces after the parentheses are where you put the body of the concrete class that implements the methods in the interface. You an also create anonymous classes that extend abstract classes and concrete classes this way.
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3419
    
  12
And just to show that you haven't created an instance of the interface, try running this.



Joanne
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

And also:

 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Anonymous classes Query
 
Similar Threads
SWT resize/modal question
JQPlus Question on Inner Classes
Question regarding inner class
Anonymous Inner class
abstract class instantiation