Anonymous Class

An anonymous class is a class not given a name and is both declared and instantiated in a single statement. You should consider using an anonymous class whenever you need to create a class that will be instantiated only once.

tip.eps Although an anonymous class can be complex, the syntax of anonymous class declarations makes them most suitable for small classes that have just a few simple methods.

An anonymous class must always implement an interface or extend an abstract class. However, you don’t use the extends or implements 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 }

Within the class body, you must provide an implementation for each abstract method defined by the interface or abstract class. Here’s an example that implements an interface named runnable, which defines a single method named run:

runnable r = new runnable()

{

public void run()

{

//code for the run method goes here

}

};

Here are a few other important facts concerning anonymous classes:

check.png An anonymous class cannot have a constructor. Thus, you cannot pass parameters to an anonymous class when you instantiate it.

An anonymous class can access any variables visible to the block within ...

Get Java For Dummies Quick Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.