Types of Inner Class

There are two types of Inner class:
1. Local classes
2. Anonymous classes

When working with Java, especially in GUI programming, multithreading, or encapsulating logic inside methods, you'll often come across local classes and anonymous classes.

Let’s break them down with simple explanations and examples.


What is a Local Class?

A local class is a class defined inside a method or a block.

public class Outer {
    void greet() {
        class Greeter {
            void sayHello() {
                System.out.println("Hello from local class!");
            }
        }
        Greeter g = new Greeter();
        g.sayHello();
    }
}

Key Features:


What is an Anonymous Class?

An anonymous class is a one-time-use class with no name, typically used to:

interface Hey {
    void run();
}

public class Main {
    public static void main(String[] args) {

        Hey task = new Hey() {
            @Override
            public void run() {
                System.out.println("Task is running (anonymous class)");
            }
        };

        task.run();
    }
}

Key Features:


Anonymous Classes Can't Be Reused

This is a common point of confusion:

interface Hey {
    void run();
}

public class Main {
    public static void main(String[] args) {

        Hey task = new Hey() {
            @Override
            public void run() {
                System.out.println("Task is running (anonymous class)");
            }
        };

        task.run();
        
		Hey task2 = new Hey(); // Error: Cannot instantiate the type Hey
    }
}

Each anonymous class is defined and used at the same point. Even if two look similar, they're considered different by the compiler.

Can You Use Anonymous Classes Without Interfaces?

Yes, you can also extend a class anonymously:

class Animal {
    void speak() {
        System.out.println("Animal sound");
    }
}
Animal dog = new Animal() {
    @Override
    void speak() {
        System.out.println("Dog barks");
    }
};
dog.speak(); // Output: Dog barks

So, anonymous classes can:

But they must extend or implement something — you can't define one without a base.


Static in Local & Anonymous Classes

In local and anonymous classes:

void show() {
    class Local {
        static final String GREETING = "Hello"; // Allowed
        // static void sayHi() {}              // Error
    }
}

When to Use Which?

Feature Local Class Anonymous Class
Has a name Yes No
Reusable Yes No
Code size Slightly bigger Compact
Use case Reuse, readability One-time quick logic
Inherits/Implements Class or interface Must extend/implement something
Can have multiple methods Yes But usually only one method

Final Tips