Last Updated: 25 September, 2022
A class that doesn't have a name is known as an anonymous class in Java. An anonymous class is always defined within another class. Hence, it is also known as an anonymous inner class.
An anonymous inner class can be useful when making an instance of an object with certain “extras”, such as overriding methods of a class or interface, without having to actually subclass a class.
📝 The anonymous inner class name is decided by the compiler.
In Java, we can create an anonymous inner class in two ways:
Syntax: Anonymous Inner Class
Example 1 : Anonymous Class Extending an Abstract Class
Output
Product Price: 2000
When we compile the above program, a class is created which extends the ProductPrice class and provides the implementation of the getProductPrice() method.
An object of the Anonymous class is created that is referred to by pdtPrice. It is a reference variable of the ProductPrice type.
The compiler will generate three .class files as given below:
We can also implement an anonymous class using an interface same as an abstract class. Let's see an example given below.
Example 2 : Anonymous Class Implementing an Interface
Instead of an abstract class, we created an interface. The rest of the implementation is the same as the above program.
Output
Product Price: 2000
That's all guys, hope this Java article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com