What is the difference between a static nested class and an inner class in Java?
An inner (non-static) class holds a hidden reference to an instance of its outer class and can use its members. A static nested class has no such link, so it can be created without an outer object, like an ordinary top-level class placed inside another for organisation.
Explain it simply
A Hostel has Rooms. A Room inside a hostel always belongs to one particular hostel building: that is an inner class. A "Warden" form template that is just kept in the hostel office, but does not need any specific building, is a static nested class.
Example
class Hostel {
private String name = "Ganga";
class Room { // inner: tied to a Hostel object
String describe() { return "Room in " + name; }
}
static class Rule { // static nested: independent
String text() { return "Lights off at 11"; }
}
}
Hostel h = new Hostel();
Hostel.Room r = h.new Room(); // needs an outer object
Hostel.Rule rule = new Hostel.Rule(); // does not
System.out.println(r.describe()); // prints: Room in Ganga
System.out.println(rule.text()); // prints: Lights off at 11What to say in the interview
"An inner class carries an implicit reference to the enclosing instance, so it can read even private outer fields, but it can leak the outer object if it outlives it. A static nested class has no outer instance and only static access to the outer class. I default to static nested, for example a Node in a LinkedList or a Builder, and use an inner class only when it really needs the outer object's state."
Common mistakes
- Making a long-lived inner class (for example a callback), which keeps the whole outer object alive.