Java › Inner Classes & Anonymous Classes
What is a static nested class, and why is it generally preferred over a non-static inner class when the nested class doesn't actually need access to the enclosing instance?
IntermediateAnswer
A static nested class is declared with the static modifier, meaning it does NOT hold an implicit reference to any specific enclosing instance and can be instantiated independently (new Outer.Nested(), no outer instance required) -- it's generally preferred over a non-static inner class whenever the nested class's logic genuinely doesn't need access to the enclosing instance's state, since it avoids the memory overhead and potential memory-leak risk of an implicit outer reference (which, for a non-static inner class, can inadvertently keep the entire outer instance alive as long as any inner instance exists), and Effective Java specifically recommends defaulting to static nested classes unless outer-instance access is genuinely required.
public class Outer {
static class Nested { // no implicit outer reference
void doWork() { System.out.println("Working independently"); }
}
}
Outer.Nested nested = new Outer.Nested(); // no outer instance needed at all
nested.doWork();Real-world example A Node class used internally by a custom LinkedList implementation is declared as a static nested class specifically because each Node instance genuinely never needs to reference the LinkedList instance itself, avoiding the unnecessary per-node memory overhead an implicit outer reference would otherwise add across potentially millions of nodes.