Yandex

Java Advanced ConceptsJava Advanced Concepts3

Java ReferenceJava Reference1

Java Anonymous Class
Basics and Examples



In Java, we often create a class, give it a name, define its methods, then use it. But what if you only need the class once — just for a quick tweak or override? That’s where anonymous classes come in.

An anonymous class in Java is a class without a name. You define and instantiate it all at once, usually when you need to override a method of an existing class or interface for one-time use.

Why Use Anonymous Classes?

Anonymous classes help reduce boilerplate code when working with simple interface implementations or abstract class extensions. They're especially useful in GUI event handling, callbacks, and quick tweaks where defining a full class would feel redundant.

Basic Syntax

The structure of an anonymous class looks like this:

Type instance = new Type() {
    // overridden methods
};

Here, Type can be an interface or a class (usually abstract).

Example 1: Anonymous Class Implementing an Interface

interface Greeting {
    void sayHello();
}

public class AnonymousDemo {
    public static void main(String[] args) {
        Greeting greet = new Greeting() {
            @Override
            public void sayHello() {
                System.out.println("Hello from Anonymous Class!");
            }
        };

        greet.sayHello();
    }
}
Hello from Anonymous Class!

Explanation:

Here, we didn’t create a separate class to implement Greeting. Instead, we provided the method body right where the object is created. Compact, clear, and direct.

Example 2: Anonymous Class Extending an Abstract Class

abstract class Animal {
    abstract void sound();
}

public class Zoo {
    public static void main(String[] args) {
        Animal dog = new Animal() {
            @Override
            void sound() {
                System.out.println("Woof! Woof!");
            }
        };

        dog.sound();
    }
}
Woof! Woof!

Explanation:

The anonymous class provides an implementation for the abstract method sound() and we’re ready to use it — no need to name the subclass at all.

Example 3: Anonymous Class with Constructor Parameters

class Person {
    String name;

    Person(String name) {
        this.name = name;
    }

    void introduce() {
        System.out.println("Hi, I'm " + name);
    }
}

public class Demo {
    public static void main(String[] args) {
        Person p = new Person("Alice") {
            @Override
            void introduce() {
                System.out.println("Hi there, I'm " + name + ", and I love Java!");
            }
        };

        p.introduce();
    }
}
Hi there, I'm Alice, and I love Java!

Explanation:

Yes — you can even pass parameters to a superclass constructor when using an anonymous class. And then, override the behavior in place.

Where Are Anonymous Classes Commonly Used?

Example 4: Runnable with Anonymous Class

public class ThreadDemo {
    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                System.out.println("Running in a thread");
            }
        };

        new Thread(r).start();
    }
}
Running in a thread

Limitations of Anonymous Classes

Anonymous Classes vs Lambda Expressions

Java 8 introduced lambda expressions which are often used in place of anonymous classes when working with functional interfaces.

// Anonymous class
Runnable r1 = new Runnable() {
    public void run() {
        System.out.println("From Anonymous Class");
    }
};

// Lambda expression
Runnable r2 = () -> System.out.println("From Lambda");

r1.run();
r2.run();
From Anonymous Class
From Lambda

Summary

Java anonymous classes allow you to define and instantiate a class in a single expression. They’re used for quick, throwaway implementations, especially when working with interfaces or abstract classes. While not always ideal for complex behavior, they shine when used sparingly for localized functionality.

QUIZ

Question 1:What is an anonymous class in Java?

Question 2:Anonymous classes can be used to implement interfaces and extend abstract classes.

Question 3:Which of the following best represents the syntax of an anonymous class?

Question 4:In which scenarios are anonymous classes commonly used?

Question 5:Anonymous classes can define constructors to initialize their own state.

Question 6:What will be the output of the following code?
Runnable r = new Runnable() {
    public void run() {
        System.out.println("Hello from anonymous thread!");
    }
};

r.run();



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M