The Plain Picture#
A small helper who only works inside one department doesn't need a desk in the main lobby.
The Real Names#
| Kind | Declared | Has access to the outer object? | Use |
|---|---|---|---|
| static nested class | static class Node { } inside another class | no | helper types: a linked list's Node, a map's Entry — the usual choice |
| inner class | class Iter { } (non-static) inside another | yes — each instance is tied to an outer object | iterators that need the outer object's data |
| local class | inside a method | can use the method's (effectively final) variables | rare |
| anonymous class | new Interface() { ... } right where it's used | same as local | one-off implementations — mostly replaced by lambdas |
Every example program in this file uses static nested classes (static class Student inside public class Oop) so that one file can
hold everything.
Anonymous class — an unnamed class created on the spot:
Comparator<String> byLength = new Comparator<String>() {
// implement the interface right here
@Override
public int compare(String a, String b) {
return Integer.compare(a.length(), b.length());
}
};
List<String> names = new ArrayList<>(List.of("Vikram", "Priya", "Al"));
names.sort(byLength);
System.out.println(names); // [Al, Priya, Vikram]That's a lot of ceremony for "compare by length". Java 8 lambdas shrink it to
names.sort((a, b) -> Integer.compare(a.length(), b.length())); — covered in Modern Java.
Gotcha: an inner (non-static) class secretly holds a reference to its outer object, which can keep the outer object alive (a memory leak
source). Make nested classes static unless they truly need the outer object.
Check yourself
2 questionsStatic nested vs inner class — what's the difference?
Show answerHide answer
An inner class instance is tied to (and holds a reference to) an outer object; a static nested class isn't.
What is an anonymous class, and what mostly replaced it?
Show answerHide answer
A class with no name, defined and instantiated in one expression; lambdas replaced most uses.