Example & Tutorial understanding programming in easy ways.

What is Anonymous Class in Java ?

Anonymous Class
An anonymous class is a local class without a name. An anonymous class is defined and instantiated in a single succinct expression using the new operator. While a local class definition is a statement in a block of Java code, an anonymous class definition is an expression, which means that it can be included as part of a larger expression, such as a method call. When a local class is used only once, consider using anonymous class syntax, which places the definition and use of the class in exactly the same place.

The Syntax for Anonymous Class
This example shows an anonymous class definition for a comparator that is passed to the sort() method in the Collections class. Assume that a List is a valid List of data that is to be sorted.

Collections.sort (aList,
new Comparator () { // implements the IF
public int compare (ObjectType o1, ObjectType o2 ) throws ..{
.... implementation for compare()
} // end of compare()
} // end of Comparator implementation
); // closed paren for sort() and end of statement semicolon
Rules:

1 An anonymous class must always extend a super class or implement an interface but it cannot have an explicit extends or implements clause.
2 An anonymous class must implement all the abstract methods in the super class or the interface.
3 An anonymous class always uses the default constructor from the super class to create an instance.

Use an anonymous class:

Anonymous classes can be time-savers and reduce the number of .java files necessary to define an application. You may have a class that is only used in a specific situation such as a Comparator. This allows an "on the fly" creation of an object.
You may find you prefer to use anonymous classes; many people use them extensively to implement listeners on GUIs.

Read More →