Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Java

Mastering Java Anonymous Inner Classes: Definition, Syntax, and Practical Examples

Mastering Java Anonymous Inner Classes

Discover how to define, implement, and leverage anonymous inner classes in Java with clear, real‑world examples.

In Java, a class can nest another class—an inner class. When that inner class has no explicit name, it is called an anonymous inner class.

Anonymous inner classes are defined inline within another class or expression. Because they lack a name, they are created only when the enclosing code runs, making them ideal for short, one‑off implementations.

The typical pattern is:

class OuterClass {
    // create an anonymous inner class instance
    Type instance = new Type(parameters) {
        // overridden methods or additional behavior
    };
}

Here, Type can be either:

  1. a superclass that the anonymous class extends
  2. an interface that the anonymous class implements

At runtime, the statement above constructs an instance of the anonymous class, which can then be used through the declared reference type.

Important: Because the declaration is an expression, the closing semicolon ends the statement, not the class body.


Example 1: Extending a Class with an Anonymous Inner Class

class Polygon {
    public void display() {
        System.out.println("Inside the Polygon class");
    }
}

class AnonymousDemo {
    public void createClass() {
        Polygon p1 = new Polygon() {
            @Override
            public void display() {
                System.out.println("Inside an anonymous class.");
            }
        };
        p1.display();
    }
}

public class Main {
    public static void main(String[] args) {
        new AnonymousDemo().createClass();
    }
}

Output

Inside an anonymous class.

In this illustration, the anonymous class extends Polygon and overrides display(). When createClass() runs, an instance of the anonymous subclass is created, and its overridden method is invoked.


Example 2: Implementing an Interface with an Anonymous Inner Class

interface Polygon {
    void display();
}

class AnonymousDemo {
    public void createClass() {
        Polygon p1 = new Polygon() {
            @Override
            public void display() {
                System.out.println("Inside an anonymous class.");
            }
        };
        p1.display();
    }
}

public class Main {
    public static void main(String[] args) {
        new AnonymousDemo().createClass();
    }
}

Output

Inside an anonymous class.

Here, the anonymous class implements the Polygon interface, providing the required method implementation in a single, concise block.


Why Use Anonymous Inner Classes?

Anonymous inner classes shine in scenarios where you need a brief, context‑specific implementation:

Benefits include:

For larger, reusable logic, consider named classes or lambda expressions (for functional interfaces) to keep the code maintainable.


Java

  1. Understanding Java’s final Keyword: Variables, Methods, and Classes
  2. Java instanceof Operator: A Comprehensive Guide
  3. Mastering Java Inheritance: Concepts, Types, and Practical Examples
  4. Understanding Java Nested Static Classes: Usage, Differences, and Examples
  5. Mastering Java’s ObjectInputStream: A Comprehensive Guide
  6. Mastering Java ObjectOutputStream: Serialization, Methods, and Practical Examples
  7. Mastering Java’s PrintStream Class: Print, Println, and Printf Explained
  8. Mastering Java Reader Class: Subclasses, Methods, and Practical Example
  9. Mastering Java Generics – Building Reusable, Type‑Safe Code
  10. Mastering Java File Operations with java.io – Creation, Reading, Writing & Deletion