Java Anonymous Class

Summary: In this tutorial, you will learn about the Java anonymous class and how to use it to make your code more concise.

Introduction to the Java anonymous class

In Java, an anonymous class is a class that has no name that extends an existing class or implements an interface.

An anonymous class allows you to declare and create the object at the same time. But you only can create a single object from the anonymous class.

Unlike a regular class, an anonymous class is an expression. It means that you need to define the anonymous class within another expression.

Let’s take an example of declaring an anonymous class.

Suppose, you have the following Person class:

public class Person {
    protected String name;

    public Person(String name) {
        this.name = name;
    }

    public void sayHi() {
        System.out.println("Hi, I'm " + name + ".");
    }
}Code language: Java (java)

The Person class has a protected field name and a method sayHi() that returns a greeting message.

The following program creates a new instance of the Person class and calls the sayHi() method:

public class App {
    public static void main(String[] args) {
        var english = new Person("John");
        english.sayHi();
    }
}Code language: Java (java)

Output:

Hi, I'm John.Code language: Java (java)

Image that you need to define a new class that extends the Person class. In that class, you want to override the sayHi() method to return a greeting message in French.

To do that, you can define a regular class that inherits from the Person class. However, since you only use that class once, defining a completely new class would be too much.

In this case, you can define an anonymous class that extends the Person class. And then you create the object of the class at the same time. Inside the anonymous class, you can override the sayHi() method of the Person class:

var french = new Person("Lionel") {
    @Override
    public void sayHi() {
        System.out.println("Salut, je m'appelle" + name + ".");
    }
};Code language: Java (java)

In this example, the anonymous class includes the following:

  • The new operator creates a new instance of the anonymous class.
  • The name of the class (Person) to extend.
  • Parentheses that contain the arguments (name) of the constructor.
  • A class declaration body that contains methods and fields of the anonymous class. In the body, we override the sayHi() method of the Person class by displaying a greeting in French.

Since an anonymous class definition is an expression, you need to end it with a semicolon (;).

Because the french variable is a reference of the object of the anonymous class, you can call the sayHi() method as follows:

french.sayHi();Code language: Java (java)

It executes the sayHi() method in the anonymous class and displays the following message on the screen:

Salut, je m'appelleLionel.Code language: Java (java)

Here’s the complete program:

public class App {
    public static void main(String[] args) {
        var english = new Person("John");
        english.sayHi();

        var french = new Person("Lionel") {
            @Override
            public void sayHi() {
                System.out.println("Salut, je m'appelle" + name + ".");
            }
        };
        french.sayHi();
    }
}Code language: Java (java)

Defining an anonymous class that implements an interface

Java allows you to define an anonymous class that implements an interface. For example, the following defines an interface Greeting that has a method greet():

public interface Greeting {
    void greet(String name);
}Code language: Java (java)

Here is how you define an anonymous class that implements the Greeting interface:

public class App {
    public static void main(String[] args) {
        var greeter = new Greeting() {
            @Override
            public void greet(String name) {
                System.out.println("Hi " + name + ". How are you?");
            }
        };
        greeter.greet("John");
    }
}Code language: Java (java)

Output:

Hi John. How are you?Code language: Java (java)

How it works:

  • First, use the new keyword creates a new instance of the anonymous class that implements the Greeting interface.
  • Second, provide an implementation of the greet() method of the Greeting interface inside the anonymous class,
  • Third, assign the instance of the anonymous class to the greeter variable.
  • Finally, call the greet() method of the anonymous class that displays a greeting on the screen.

Summary

  • Use a Java anonymous class to define a class with no name and create an object of that class at the same time to make your code more concise.
Was this tutorial helpful ?