Lesson 22 / 38
Nested & Inner Classes
Distinguish static nested classes, non-static inner classes, local classes and anonymous classes, and see when each earns its keep.
Static nested vs inner
A static nested class (static class Node {...}) is just a normal class namespaced inside another — it has no link to an outer instance. A non-static inner class is tied to an enclosing instance and can access its fields directly, but needs outer.new Inner() to create.
An inner class in action
Because Iterator here is non-static, it can read items directly without the container passing it in explicitly.
class Playlist {
private final List<String> items = new ArrayList<>();
class Cursor { // non-static inner class
int pos = 0;
String next() { return items.get(pos++); }
}
}
Playlist p = new Playlist();
Playlist.Cursor c = p.new Cursor();Local & anonymous classes
A local class is declared inside a method body, visible only there. An anonymous class (new Comparator<String>() { ... }) declares and instantiates an unnamed one-off subclass in a single expression — largely superseded by lambdas for functional interfaces, but still useful for classes with multiple methods or state.