When to use which type of nested class

Java offers four types of nested classes to help you keep related logic together. But when should you use each of them?

Let’s simplify this with real-world cases and examples.


1. Static Nested Class

When to Use:

Example:

class Utils {
    static class Logger {
        static void log(String msg) {
            System.out.println("LOG: " + msg);
        }
    }
}

2. Inner Class (member inner class ) (Non-static Nested Class)

When to Use:

Example:

class Engine {
    private int rpm = 6000;
    class Piston {
        void move() {
            System.out.println("Piston moving at " + rpm + " rpm");
        }
    }
}

Remember:

You must create an object of the outer class to use the inner class.

3. Local Inner Class

When to Use:

Example:

void calculate() {
    class Multiplier {
        int timesTwo(int x) {
            return x * 2;
        }
    }
    Multiplier m = new Multiplier();
    System.out.println(m.timesTwo(5));
}

Think of it as:

A private, one-method-only class that’s hidden from the rest of your app.

4. Anonymous Inner Class

When to Use:

Example:

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(); // works
        
		Hey task2 = new Hey(); // Error: Cannot instantiate the type Hey
    }
}

Perfect for:

Replacing full class definitions when the logic is quick and single-use.

Summary