English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, you will learn about anonymous classes in Java through examples.
In Java, a class can contain another class called a nested class. A nested class can be created without providing any name.
A nested class without any name is called an anonymous class.
An anonymous class must be defined within another class. Therefore, it is also called an anonymous inner class. Its syntax is:
class outerClass { //Define an anonymous class object1 = new Type(parameterList) { //The body of the anonymous class }; }
An anonymous class usually inherits a subclass or implements an interface.
Here,Type(Type)Can be
The superclass inherited by the anonymous class
The interface implemented by the anonymous class
The above code creates an object of the anonymous class at runtime1.
Note:An anonymous class is defined within an expression. Therefore, a semicolon is used at the end of the anonymous class to indicate the end of the expression.
class Polygon { public void display() { System.out.println("Inside the Polygon class"); } } class AnonymousDemo { public void createClass() { //Create an anonymous class, inheriting the class Polygon Polygon p1 = new Polygon() { public void display() { System.out.println("The internal of the anonymous class."); } }; p1.display(); } } class Main { public static void main(String[] args) { AnonymousDemo an = new AnonymousDemo(); an.createClass(); } }
Output result
The internal of the anonymous class
In the above example, we created a class Polygon. It has only one method display().
Then, we created an anonymous class that inherits the class Polygon and overrides the display() method.
When we run this program, an object of the anonymous class p will be created1. Then, the object calls the display() method of the anonymous class.
interface Polygon { public void display(); } class AnonymousDemo { public void createClass() { //Implementation of the interface by an anonymous class Polygon p1 = new Polygon() { public void display() { System.out.println("The internal of the anonymous class."); } }; p1.display(); } } class Main { public static void main(String[] args) { AnonymousDemo an = new AnonymousDemo(); an.createClass(); } }
Output result
The internal of the anonymous class
In the above example, we created an anonymous class that implements the Polygon interface.
In the anonymous class, create objects as needed. That is, create objects to perform certain specific tasks. For example,
Object = new Example() { public void display() { System.out.println("Anonymous class overrides the display() method."); } };
Here, when we need to override the display() method, an object of the anonymous class will be dynamically created.
Anonymous classes also help us make the code concise.