Static Nested vs Inner Classes
The real difference between a static nested class and an inner class, and why static is the safer default.
Open this lesson in the learning hubKey points
- A
staticnested class is just a top-level class living inside another for naming. No link to any outer object. - An inner (non-static) class holds a hidden reference to its outer instance, which is how it reads outer fields.
- That hidden reference keeps the outer object alive. An inner class stored in a long-lived cache is a classic leak.
- Default to
static. Drop the keyword only when you genuinely need access to the enclosing instance. - Local and anonymous classes capture local variables, which must be final or effectively final.
- A lambda is not an inner class. Inside a lambda,
thisstill refers to the enclosing object.
Example
public class Main {
private final String label = "outer state";
static class Nested { // no link to any Main instance
String hello() { return "static nested: standalone, like a top-level class"; }
}
class Inner { // carries a hidden Main.this reference
String hello() { return "inner: can read " + label; }
}
public static void main(String[] args) {
System.out.println(new Nested().hello()); // no outer object needed
Main outer = new Main();
Main.Inner inner = outer.new Inner(); // needs an outer object
System.out.println(inner.hello());
int captured = 42; // effectively final
Runnable local = () -> System.out.println("lambda captured " + captured);
local.run();
}
}
Make nested classes static unless they truly need the enclosing instance.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the OOP course, and every lesson in it is listed on the OOP contents page.