All topics
library
intermediate

Inner Classes: Static, Member, Local, Anonymous

Know the four types of inner classes, when each is appropriate, and their relationship to the enclosing instance.

Java supports four types of nested classes:

Static nested = a tenant in an office building (uses the address but has their own key, doesn't need the landlord). Member inner = a personal assistant (always tied to a specific boss, has access to the boss's office).

Key Concepts

1
1. Static nested class — declared static inside another class. No reference to the enclosing instance. Behaves like a top-level class that's scoped inside another for packaging. Use for helper classes that don't need the outer's state (e.g., Map.Entry).
2
2. Member inner class (non-static) — declared without static. Holds an implicit reference to the enclosing instance (OuterClass.this). Can access all outer fields/methods including private. Each instance is tied to an outer instance. Memory leak risk: the inner keeps the outer alive.
3
3. Local inner class — declared inside a method. Can access local variables of the method IF they are final or effectively final. Rare in modern code — lambdas replaced most use cases.
4
4. Anonymous inner class — a local class without a name, declared and instantiated in a single expression. Common pre-Java-8 for event handlers, callbacks, Comparators. Largely replaced by lambdas for functional interfaces.
5
Memory leak concern: non-static inner classes hold a reference to the enclosing object. If the inner class instance outlives the outer (e.g., stored in a collection, returned from a method), the outer can't be garbage collected. This is a common source of memory leaks in Android development.
6
Prefer static nested classes unless you genuinely need access to the enclosing instance.