How to define anonymous classes in Java

bankymono
2 min readApr 11, 2024

An anonymous class is a class that is defined without a name. It implements an interface or extends a class while also instantiating an object. They are created inline and can be used once.

An anonymous class that implements the interface MyInterface. An instance of the anonymous class is then created and assigned to the variable objectName

Although they can be used to extend classes, they are mostly used to implement interfaces.

Let us create an interface called MyInterface in an org.example package.

package org.example;

public interface MyInterface {
void sayHello();

void sayGoodBye();
}

We can still create a class that implements this interface, without necessarily creating the class in a separate file.

Creating an Anonymous class

A normal step would be to create a class in a separate java file that implements the Interface, then create instances of this class.

However, we do not want to create a class in a separate java file to implement this interface, but still want to instantiate an object from a class that implements this interface. Let us can create an anonymous class to achieve this.

We can implement this interface with an anonymous class inside a class we call Main(you can call the class anything, I just chose Main in this example), created in the same package org.example. This is where we define our main method .

package org.example;

public class Main {
public static void main(String[] args) {

MyInterface anonObject = new MyInterface() { (1)
@Override
public void sayHello() {
System.out.println("Hello from Main :) :)");
}

@Override
public void sayGoodBye() {
System.out.println("Good bye for now!");
}
}; (2)

anonObject.sayHello();
anonObject.sayGoodBye();
}
}

In the code above, inside our main method, we used an anonymous class to implement the interface MyInterface. In the anonymous class, we implemented the abstract methods of MyInterface — sayHello() and sayGoodBye(). The definition of the anonymous class starts with the curly brace at(1) and ends with the semicolon at(2)

We also created an instance of the anonymous class and assigned it to a variable named anonObject. We then called the methods of the object instance.

Here is the link to the github repo for the code.

--

--