Working with Nested and Inner Classes

1. Defining Static Nested Classes

Example: Static nested

public class Outer {
    static class Helper {
        void run() { System.out.println("helper"); }
    }
}
Outer.Helper h = new Outer.Helper();
AspectDetail
Outer instanceNot required
AccessOuter's static members only
Use caseLogical grouping, builders, helper types

2. Defining Non-Static Inner Classes

AspectDetail
Outer instanceRequired (implicit reference)
Constructionouter.new Inner()
AccessAll outer members (incl. private)
Static membersAllowed since Java 16

3. Creating Local Classes

Example: Local class

void process(List<String> items) {
    class Counter { int n = 0; void inc() { n++; } }
    Counter c = new Counter();
    items.forEach(s -> c.inc());
}
AspectDetail
ScopeBlock where declared
AccessEffectively final local vars

4. Creating Anonymous Classes

Example: Anonymous class

Runnable r = new Runnable() {
    @Override public void run() { System.out.println("hi"); }
};
AspectDetail
No nameDefined and instantiated in one expression
Has thisRefers to anonymous instance (unlike lambda)
Use caseMultiple methods or fields needed (else use lambda)

5. Accessing Outer Class Members

FromAccess
Inner classAll outer members
Static nestedStatic outer members only
AnonymousEffectively-final locals + outer members

6. Understanding .this Syntax

Example: Outer.this

class Outer {
    int x = 1;
    class Inner {
        int x = 2;
        void show() {
            System.out.println(x);            // 2
            System.out.println(Outer.this.x); // 1
        }
    }
}
FormMeaning
thisInner instance
Outer.thisEnclosing outer instance

7. Using Inner Classes for Callbacks

PatternUse
Listener / observerImplements callback interface, accesses outer state
IteratorInner class returning Iterator<T>

8. Converting Anonymous to Lambda

AnonymousLambda
new Runnable() { run() {...} }() -> {...}
SAM onlyRequired for lambda
this bindingAnonymous: self; Lambda: enclosing

9. Understanding Nested Class Use Cases

TypeWhen to use
Static nestedBuilder, helper, no outer state needed
InnerTight coupling with outer state (e.g., iterator)
LocalScoped helper inside one method
AnonymousMulti-method ad-hoc impl (else lambda)