Java Anonymous Classes
In Java, a class can contain another class and be instantiated directly without providing any class name.
It is mainly used to create an object to perform a specific task when needed, which makes the code more concise.
Anonymous classes are classes that cannot have names. They cannot be referenced, and can only be used at creation time withnewa statement to declare them.
Anonymous class syntax format:
class outerClass {
// 定义一个匿名类
object1 = new Type(parameterList) {
// 匿名类代码
};
}
The above code creates an anonymous class object object1. The anonymous class is defined as an expression, so the end is with a semicolon;to end.
Anonymous classes usually inherit a parent class or implement an interface.

Anonymous class inheriting a parent class
In the following example, a Polygon class is created. This class has only one method, display(). The AnonymousDemo class inherits the Polygon class and overrides its display() method:
Example
public void display() {
System.out.println("Inside the Polygon class");
}
}
class AnonymousDemo {
public void createClass() {
// The created anonymous class inherits the Polygon class
Polygon p1 = new Polygon() {
public void display() {
System.out.println("Inside the anonymous class.");
}
};
p1.display();
}
}
class Main {
public static void main(String[] args) {
AnonymousDemo an = new AnonymousDemo();
an.createClass();
}
}
When the above code is executed, an object p1 of the anonymous class is created. This object calls the anonymous class's display() method, and the output is:
Inside an anonymous class.
Anonymous class implementing an interface
The following example creates an anonymous class that implements the Polygon interface:
Example
public void display();
}
class AnonymousDemo {
public void createClass() {
// The anonymous class implements an interface
Polygon p1 = new Polygon() {
public void display() {
System.out.println("Inside the anonymous class.");
}
};
p1.display();
}
}
class Main {
public static void main(String[] args) {
AnonymousDemo an = new AnonymousDemo();
an.createClass();
}
}
The output is:
Inside an anonymous class.Other extensions