Advertisement
Online Test Banks
Score higher
See Online Test Banks
eLearning
Learning anything is easy
Browse Online Courses
Mobile Apps
Learning on the go
Explore Mobile Apps
Dummies Store
Shop for books and more
Start Shopping

How to Use an Anonymous Class in Java

An anonymous class in Java 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.

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:

  • 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 which the anonymous class is declared, including local variables.

  • An anonymous class can also access methods of the class that contains it.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win an iPad Mini. Enter to win now!