Java Anonymous Classes
In Java, it is possible to implement a class that contains another class without providing any class name and directly instantiate it.
This is primarily used to create an object to perform specific tasks when needed, making the code more concise.
Anonymous classes are classes without a name. They cannot be referenced and can only be declared using the new statement when they are created.
Anonymous class syntax format:
class outerClass {
// Define an anonymous class
object1 = new Type(parameterList) {
// Anonymous class code
};
}
The above code creates an anonymous class object named object1. Since anonymous classes are defined in expression form, they end with a semicolon ;
.
Anonymous classes typically inherit from a superclass or implement an interface.
Anonymous Class Inheriting a Superclass
In the following example, a Polygon class is created, which has only one method display(). The AnonymousDemo class extends the Polygon class and overrides the display() method of the Polygon class:
Example
class Polygon {
public void display() {
System.out.println("Inside the Polygon class");
}
}
class AnonymousDemo {
public void createClass() {
// The anonymous class extends the Polygon class
Polygon p1 = new Polygon() {
public void display() {
System.out.println("Inside an anonymous class.");
}
};
p1.display();
}
}
class Main {
public static void main(String[] args) {
AnonymousDemo an = new AnonymousDemo();
an.createClass();
}
}
When the above code is executed, the anonymous class object p1 is created, which calls the display() method of the anonymous class, 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
interface Polygon {
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 an 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.