Java Inner Classes

Mastering nested structures: Member, Static Nested, Local, and Anonymous classes

1. What is an Inner Class?

An Inner Class (or Nested Class) is a class declared inside another class or interface. It allows you to logically group classes that are only used in one place, enhancing encapsulation and readability.

1. Member Inner

Declared inside a class, outside methods. Needs an outer object instance to exist.

2. Static Nested

Declared with static. Independent of outer class instances.

3. Local Inner

Declared inside a method body. Scope is restricted to that method.

4. Anonymous

A class without a name declared and instantiated in a single expression.

2. Interactive Code & Instantiation Explorer

Click through the tabs to see how each inner class type is instantiated and how it accesses outer members.

class Outer {
    private String secret = "Outer Private Secret";

    // Member Inner Class
    class Inner {
        void reveal() {
            System.out.println(secret); // Directly accesses private outer field!
        }
    }
}

// Instantiation Syntax: Requires Outer Instance
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.reveal();
class Outer {
    static String appName = "JavaApp";

    // Static Nested Class
    static class Nested {
        void display() {
            System.out.println("App Name: " + appName);
            // Cannot access non-static outer members directly!
        }
    }
}

// Instantiation Syntax: No Outer Instance Needed!
Outer.Nested nested = new Outer.Nested();
nested.display();
class Outer {
    void processData() {
        int factor = 2; // Must be effectively final

        // Local Class defined inside method
        class Calculator {
            int multiply(int val) { return val * factor; }
        }

        Calculator calc = new Calculator();
        System.out.println("Result: " + calc.multiply(10));
    }
}
interface Greeting {
    void sayHello();
}

class Main {
    public static void main(String[] args) {
        // Anonymous Class implementing Greeting interface on the fly
        Greeting g = new Greeting() {
            public void sayHello() {
                System.out.println("Hello from Anonymous Class!");
            }
        };
        g.sayHello();
    }
}
> Click "Simulate Code" to see the output here...