Anonymous Class in Java

Anonymous class in Java is a class without name. Its name is decided by the compiler. It enables us to declare and instantiate the class at the same time. It is like local class except that it does not have any name. We can use it only once.

Anonymous class is also known as anonymous inner class in java. It is called anonymous inner class because it is defined inside another class.

How to Create Anonymous Class in Java

Anonymous class can be created in following two ways.

1. Using Class
2. Using Interface

Java Anonymous Class Example Using Class


Output

Anonymous Class in Java

When the above code is compiled, an anonymous class is created and its name is decided by the compiler. This anonymous class extends Parent class and overrides show() method.

In above example an object of anonymous class is created and its reference is stored in reference variable p of Parent class.

I have decompiled the .class file generated by compiler for the anonymous class. It contains the following code.

Java Anonymous Class Example Using Interface


When the above code is compiled, an anonymous class is created and its name is decided by the compiler. This anonymous class implements Parent interface and overrides show() method.

In above example an object of anonymous class is created and its reference is stored in reference variable p of Parent interface.

I have decompiled the .class file generated by compiler for the anonymous class. It contains the following code.

What is the purpose of anonymous class in Java?

You may be thinking that above work can also be done by creating a separate class and then extending Parent class. Why we have created anonymous class? Actually it is quicker to create an anonymous class then creating a separate class. Anonymous inner class is useful when we want to override a small amount of functionality (like one method) of parent class. It also makes our code more concise.

If you find anything missing or incorrect in above tutorial then please mention it by commenting below. 

2 thoughts on “Anonymous Class in Java”

  1. Hanumanth jalsa

    In the "Example using interface", we created reference using constructor of interface,how invoking constructor of interface is correct??

    1. Yes you are right, according to rule we can't create instance of interface. But for creating anonymous class we have to follow the above syntax. Here anonymous class object is created.

Leave a Comment

Your email address will not be published. Required fields are marked *