J2EEOnline J2EE   





Java2 Certification  «Prev  Next»
Lesson 10Inner classes and Anonymous Classes
ObjectiveExplain anonymous classes as a special case of inner classes.
Anonymous classes
Anonymous classes are a special case of local inner classes that are declared without a name. They are quick-and-dirty single-use classes that are created and defined at the same time. They are typically used to declare an instance of a class that implements an event listener interface or extends an event adapter class. There are two forms for their syntax, depending on whether they implement an interface or extend another class:

Implementing an interface
new InterfaceName() {
 // Implement interface methods
}
new SuperClassName(arguments) {
 // Class body
}
In the first form, the anonymous class is declared as implementing the specified interface name. No implements clause is used and the interface name is supplied as the type of object being created. The anonymous class is responsible for implementing all of the methods of the interface. When an anonymous inner class is defined as an interface, the Object class is its direct superclass. Since the Object class does not have a constructor that takes arguments, no arguments may be supplied when an anonymous class is created as an interface.
In the second form, the superclass of the class being defined is specified. No extends clause is used. The arguments (if any) that are supplied are passed to the superclass constructor when the object is created. The superclass must have a constructor with a signature that accepts the arguments. Since the class being declared does not have a name, no constructor is specified in the class body. An anonymous class may not have any modifiers.
The Anonymous program illustrates the use of anonymous inner classes.