All 15 Inner Classes & Anonymous Classes questions
More in Inner Classes & Anonymous Classes
Advertisement
Back to results for “Design Patterns in Java”
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?

Intermediate

Answer

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.

Common follow-ups: What's the actual memory cost (in bytes) of the implicit outer reference a non-static inner class carries?;How would you convert an existing non-static inner class to static if you later realize it doesn't actually need outer access?