Anonymous Class

Anonymous Class

A school program needs reliable data and clear rules. An anonymous class defines and creates an unnamed implementation in one expression. It suits a small one-off capability without a separate named class.

  1. Understand

    An anonymous class defines and creates an unnamed implementation in one expression.

  2. Apply

    Trace the Java example, predict its output and explain the result before running it.

  3. Avoid mistakes

    Captured local variables must be final or effectively final. Not every anonymous class can be replaced by a lambda.

Anonymous Class

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?

  • GUI applications (like Swing or Android development) for button click handlers
  • Thread creation via Runnable interface
  • Quick sorting with custom comparators
  • Callbacks in frameworks and libraries

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

  • Cannot define constructors (because they have no name)
  • Harder to debug (no class name in stack trace)
  • Only one instance can be created per definition
  • Not reusable — you can’t instantiate it again elsewhere

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.

Important boundaries and mistakes

Captured local variables must be final or effectively final. Not every anonymous class can be replaced by a lambda.

Try the school example

Before running this Java program, write down each line you expect to see. Identify the value, branch, object or exception responsible for each line. Then explain whether the following assumption is valid: Captured local variables must be final or effectively final.

Java 17 · Main.java · complete practice program

public class Main  {
  interface Named  {
    String label();
  }
  public static void main(String[] args)  {
    Named n = new Named()  {
      public String label()  {
        return "Diya";
      }
    }
    ;
    System.out.println(n.label());
  }
}

Worked answer and reasoning

Java 17 · Main.java · source repeated for this answer

public class Main  {
  interface Named  {
    String label();
  }
  public static void main(String[] args)  {
    Named n = new Named()  {
      public String label()  {
        return "Diya";
      }
    }
    ;
    System.out.println(n.label());
  }
}

Expected output

Diya

An anonymous class defines and creates an unnamed implementation in one expression. It suits a small one-off capability without a separate named class.

Captured local variables must be final or effectively final. Not every anonymous class can be replaced by a lambda.

Run with javac Main.java, then java Main. The declaration of Main names the class; main starts the example, and println writes a complete output line.

Check your understanding

For the complete practice program in this lesson, which output is expected on Java 17?
Choose one answer. You can try again.

Answer and explanation

Diya

An anonymous class defines and creates an unnamed implementation in one expression. It suits a small one-off capability without a separate named class. Captured local variables must be final or effectively final. Not every anonymous class can be replaced by a lambda.

What to remember

An anonymous class defines and creates an unnamed implementation in one expression. It suits a small one-off capability without a separate named class. Captured local variables must be final or effectively final. Not every anonymous class can be replaced by a lambda.

Related explanations: Java Variables, Java If Statement - Syntax and Examples, Java Class - Blueprint of Objects, Exceptions in Java Introduction.

Supporting documentation: Official Java learning guide and Java 17 language specification.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Singleton Class →