An anonymous class in Java is a class that is not named, and is declared and created in a single expression. You must use an anonymous class whenever you need to create a class that will be created only once.
Although an anonymous class can be complex, the syntax for declaring an anonymous class makes them most suitable for small classes that have just a few simple methods.
An anonymous class should always implement an interface or extend an abstract class. However, you do not use the extension or implement the keyword to create an anonymous class. Instead, you use the following syntax to declare and instantiate an anonymous class:
new interface-or-class-name() { class-body }
Inside the body of the class, you must provide an implementation for each abstract method defined by the interface or abstract class. Here is an example that implements an interface called runnable that defines a single method called run:
runnable r = new runnable() { public void run() {
Here are a few other important facts about anonymous classes:
An anonymous class cannot have a constructor. Thus, you cannot pass parameters to an anonymous class when you create it.
An anonymous class can access any variables that are visible to the block in which the anonymous class is declared, including local variables.
An anonymous class can also access the methods of the class containing it.
source share