How to Create an Anonymous Class in Java

By Doug Lowe

Anonymous inner classes (usually just called anonymous classes) are probably the strangest feature of the Java programming language. The first time you see an anonymous class, you’ll almost certainly think that someone made a mistake and that the code can’t possibly compile. But compile it does, and it even works. When you get the hang of working with anonymous classes, you’ll wonder how you got by without them.

An anonymous class is a class that’s defined on the spot, right at the point where you want to instantiate it. Because you code the body of the class right where you need it, you don’t have to give it a name. (That’s why it’s called an anonymous class.)

The basic form for declaring and instantiating an anonymous class is this:

new ClassOrInterface() { class-body }

As you can see, you specify the new keyword followed by the name of a class or interface that specifies the type of the object created from the anonymous class.

This class or interface name is followed by parentheses, which may include a parameter list that’s passed to the constructor of the anonymous class. Then you code a class body enclosed in braces. This class body can include anything that a regular class body can include: fields, methods, and even other classes or interfaces.

Here’s an example of a simple anonymous class:

public class AnonClass
 public static void main(String[] args)
  Ball b = new Ball()
    public void hit()
     System.out.println("You hit it!");
 interface Ball
  void hit();

In this example, interface named Ball is created that has a single method named hit. Then, back in the main method, a variable of type Ball is declared and an anonymous class is used to create an object. The body of the anonymous class consists of an implementation of the hit method that simply displays the message You hit it! on the console.

After the anonymous class is instantiated and assigned to the b variable, the next statement calls the hit method.When you run this program, the single line You hit it! is displayed on the console.

Here are some things to ponder when you work with anonymous classes:

  • You can’t create a constructor for an anonymous class, because the anonymous class doesn’t have a name. What would you call the constructor, anyway?

  • You can’t pass parameters if the anonymous class is based on an interface. That makes sense; interfaces don’t have constructors, so Java wouldn’t have anything to pass the parameters to.

  • An assignment statement can use an anonymous class as shown in this example. In that case, the anonymous class body is followed by a semicolon that marks the end of the assignment statement. Note that this semicolon is part of the assignment statement, not the anonymous class.

  • An anonymous class is a special type of inner class; like any inner class, it automatically has access to the fields and methods of its outer class.

  • An anonymous class can’t be static.