Java.Core.What are “anonymous classes” ? Where are they used ?

What are Anonymous Classes in Java?

An anonymous class in Java is a class that does not have a name and is declared and instantiated in a single expression. It is mainly used for one-time use implementations of interfaces or abstract classes.


Features of Anonymous Classes

✅ Declared and instantiated in one step (no separate class definition).
✅ Can extend a class or implement an interface but not both at the same time.
✅ Has access to outer class members, including private fields.
✅ Can access local variables if they are final or effectively final.
✅ Cannot have constructors (since it has no name).


Where Are Anonymous Classes Used?

✅ When you need a short-lived class (used once).
✅ Event handling in GUI applications (e.g., Swing/AWT).
✅ Thread creation and execution.
✅ Callback implementations in functional programming.


1. Anonymous Class Implementing an Interface

interface Greeting {
    void sayHello();
}

public class Main {
    public static void main(String[] args) {
        // Creating an anonymous class that implements Greeting
        Greeting greeting = new Greeting() {
            public void sayHello() {
                System.out.println("Hello from an anonymous class!");
            }
        };

        greeting.sayHello();
    }
}

Output:

Hello from an anonymous class!

✅ Used when a full class definition is unnecessary.

2. Anonymous Class Extending a Class

abstract class Animal {
    abstract void makeSound();
}

public class Main {
    public static void main(String[] args) {
        // Creating an anonymous class extending Animal
        Animal dog = new Animal() {
            void makeSound() {
                System.out.println("Bark!");
            }
        };

        dog.makeSound();
    }
}

Output:

Bark!

✅ Used when extending an abstract class but only need a single instance.

3. Anonymous Class for Event Handling (GUI Example)

import javax.swing.*;

public class Main {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Button Example");
        JButton button = new JButton("Click Me");

        button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent e) {
                System.out.println("Button Clicked!");
            }
        });

        frame.add(button);
        frame.setSize(200, 200);
        frame.setLayout(null);
        frame.setVisible(true);
    }
}

✅ Anonymous classes are commonly used in GUI programming for event handling.
✅ This avoids creating separate listener classes.

4. Anonymous Class in Thread Creation

public class Main {
    public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
            public void run() {
                System.out.println("Thread is running...");
            }
        });

        thread.start();
    }
}

Output:

Thread is running...

✅ Used in multithreading to avoid separate class files for Runnable implementations.

5. Anonymous Class Can Access Outer Class Members

class Outer {
    private String message = "Hello from Outer!";

    void display() {
        new Thread(new Runnable() {
            public void run() {
                System.out.println(message); // ✅ Can access private fields
            }
        }).start();
    }
}

public class Main {
    public static void main(String[] args) {
        Outer outer = new Outer();
        outer.display();
    }
}

Output:

Hello from Outer!

✅ Anonymous classes can access private fields of the enclosing class.

6. Anonymous Classes Cannot Have Constructors

Since an anonymous class has no name, it cannot define a constructor. However, it can use instance initializers (a {} block) for initialization.

abstract class Person {
    abstract void show();
}

public class Main {
    public static void main(String[] args) {
        Person p = new Person() {
            { // Instance initializer
                System.out.println("Anonymous class created!");
            }

            void show() {
                System.out.println("Inside show method.");
            }
        };

        p.show();
    }
}

Output:

Anonymous class created!
Inside show method.

✅ Instance initializers ({}) are used instead of constructors.

Key Differences: Anonymous Class vs. Regular Class

FeatureAnonymous ClassRegular Class
Has a Name?❌ No✅ Yes
Can Have Multiple Instances?❌ No (usually single-use)✅ Yes
Can Have Constructors?❌ No✅ Yes
Can Extend & Implement Simultaneously?❌ No✅ Yes
Common Use CasesEvent handling, short-lived objectsReusable class definitions

Final Answer

✔ An anonymous class is an inline implementation of an interface or an abstract class, without a name.
✔ It is mainly used for event handling, threading, and short-lived implementations.
✔ It can access outer class members and effectively final local variables.
✔ It cannot have constructors, but it can use instance initializers ({} blocks).

This entry was posted in Без рубрики. Bookmark the permalink.