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
class Parent { void show() { System.out.println("Parent"); } } class Demo { public static void main(String...s) { //creating anonymous inner class Parent p=new Parent() { void show() { System.out.println("Anonymous Class"); } }; p.show(); } }
Output
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.
import java.io.PrintStream; final class Demo$1 extends Parent { void show() { System.out.println("Anonymous Class"); } }
Java Anonymous Class Example Using Interface
interface Parent { void show(); } class Demo { public static void main(String...s) { //creating anonymous inner class Parent p=new Parent() { public void show() { System.out.println("Anonymous Class"); } }; p.show(); } }
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.
import java.io.PrintStream; final class Demo$1 implements Parent { public void show() { System.out.println("Anonymous Class"); } }
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.
In the "Example using interface", we created reference using constructor of interface,how invoking constructor of interface is correct??
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.