• Post Reply Bookmark Topic Watch Topic
  • New Topic

anonymous class  RSS feed

 
sankar singh
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anyone pls share with us, what is anonymous class and give an example for that?

Regards,

Sankar. S
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16057
88
Android IntelliJ IDE Java Scala Spring
 
Rob Spoor
Sheriff
Posts: 21133
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
An anonymous class is a subclass of an existing class or an implementation of an interface that does not have a name of its own. When compiled, it will result in class files called <MainClass>$1.class etc.

Examples:

javax.swing.AbstractAction is an abstract class with one abstract method, actionPerformed. Here you create an anonymous subclass which defines an implementation for the abstract method.


java.awt.event.ActionListener is an interface with one method, actionPerformed. Here you create an anonymous implementation which defines an implementation for the abstract method. When implementing interfaces anonymously, you have to implement ALL methods. That's why most event listeners have adapter classes which implement all methods, so you override only those you need.

Please keep the following in mind for anonymous classes:
  • You can only use constructors of the parent class. When implementing an interface, there is only the default constructor.
  • You can give the anonymous class public methods or fields, but these can only be used inside the class itself. Outside the class, all public members are unknown since the class cannot be cast. Where would you cast it to?

  •  
    It is sorta covered in the JavaRanch Style Guide.
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!