Programming Language

Explanation and Example Of Anonymous Classes In Java

In Java, anonymous classes are more precisely known as anonymous inner classes. Always remember, without the “inner”, there’s no such thing as anonymous classes. This distinction is significant because anonymous inner classes mean that they are defined within another class.

Basically, anonymous inner classes are those inner classes that are declared without using any class name at all, and due to this fact, they are called anonymous classes. Beside this, anonymous inner classes also have some pretty unusual syntax.

Here is an example with a few codes of an anonymous inner class.

Class DeveloperTest{

public void read() {

System.out.println(“DeveloperTest!”);

}

}

 

classForum{

/* This creates an anonymous inner class: */

DeveloperTest dInstance = new    DeveloperTest () {

public void read() {

System.out.println(“anonymous DeveloperTest“);

}

};

}

In the above code, you can clearly see that there are 2 classes – one called Forum and another called DeveloperTest. The DeveloperTest class is pretty straightforward – there’s just an easy procedure called “read()” that prints the text “DeveloperTest!” when called.

However, the code that you really need to look carefully at is inside the Forum class, which is highlighted in the color green. You may think that we are creating an instance of the DeveloperTest class called dInstance in that code, however, what’s really happening in that there is creation of an instance of an anonymous class.

In the above code, we have created an instance of a subclass, also called as a child class of the DeveloperTest class. Here the most critical thing to understand is that this instance (dInstance) is actually an instance of an anonymous child class of the DeveloperTest class.

An anonymous inner class- Reason behind the name

The major reason that why it’s known an anonymous inner class is that the class that we have now created is without any name! We created an instance of the class, however, we did not emphasize to give a name to the class. We just have a reference variable (in the above example, it is dInstance) for the anonymous inner class.

Leave a Reply