0
0
JavaConceptBeginner · 3 min read

What is Anonymous Class in Java: Simple Explanation and Example

An anonymous class in Java is a class without a name that is declared and instantiated all at once, usually to override or implement methods on the spot. It is useful for creating quick, one-time-use objects without writing a full class separately.
⚙️

How It Works

Imagine you want to create a helper object just once, like a quick tool you use and then discard. Instead of writing a full class with a name, you write an anonymous class directly where you need it. This class has no name and is created inside a method or expression.

It works by extending a class or implementing an interface right where you create the object. You provide the method implementations immediately, so the Java compiler creates a hidden class behind the scenes. This saves time and keeps your code cleaner when you only need a small custom behavior once.

💻

Example

This example shows an anonymous class implementing the Runnable interface to run a simple task in a new thread.

java
public class Main {
    public static void main(String[] args) {
        Runnable task = new Runnable() {
            @Override
            public void run() {
                System.out.println("Hello from anonymous class!");
            }
        };
        Thread thread = new Thread(task);
        thread.start();
    }
}
Output
Hello from anonymous class!
🎯

When to Use

Use anonymous classes when you need a quick implementation of an interface or subclass without cluttering your code with a full class. They are perfect for event listeners, callbacks, or small tasks like sorting or threading.

For example, in graphical user interfaces, you often use anonymous classes to handle button clicks. They keep your code short and focused on the specific action you want to perform.

Key Points

  • Anonymous classes have no name and are declared and instantiated in one step.
  • They extend a class or implement an interface on the spot.
  • Useful for short, one-time use objects like event handlers or threads.
  • Keep code concise by avoiding separate class files.

Key Takeaways

Anonymous classes let you create quick, unnamed classes for one-time use.
They are declared and instantiated in a single expression.
Ideal for implementing interfaces or extending classes without extra files.
Commonly used for event handling, callbacks, and threading tasks.