Anonymous Inner Class in Java

An anonymous it is an inner class without a name and for which only a single object is created. 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.

There are two classes in the program: testDemo and outerDemo. testDemo is an abstract class with an abstract method display().outerDemo is a class that contains a method outerDisplay().

In the outerDisplay() method, an instance of an anonymous inner class is created using the testDemo abstract class. This anonymous inner class overrides the display() method of testDemo with its own implementation, which simply prints the message "Test Display".

Finally, the display() method of the anonymous inner class is called using the object o.

Anonymous inner classes are useful when a class needs to be created and used only once. They are particularly useful for providing implementations of interfaces or abstract classes. They allow for the creation of an object with a single defined behavior without the need to create a separate class.

Source Code

//Anonymous Inner Class
abstract class testDemo {
    abstract void display();
class outerDemo {
    public void outerDisplay() {
        testDemo o =new testDemo() {
            public void display() {
                System.out.println("Test Display");
public class anonymousInner {
    public static void main(String[] args) {
        outerDemo o =new outerDemo();


Test Display
To download raw file Click Here

Basic Programs