Static Nested Classes
TL;DR
- A Static Nested Class is a class declared inside another class, marked with the
statickeyword. - It acts exactly like a normal top-level class, it just happens to be nested for organizational packaging.
- Crucially, it does not have access to the instance variables of the outer class, eliminating the risk of memory leaks.
Concept
A Static Nested Class is essentially a top-level class that has been tucked inside another class for namespace convenience.
For example, LinkedList has a Node class. Node is only used by LinkedList, so it makes sense to nest it. Because a Node doesn’t need to know anything about the LinkedList that owns it (it just holds data and a pointer to the next node), it should be a Static Nested Class.
Because it is static, you do NOT need an instance of the outer class to create an instance of the static nested class.
Examples
public class University {
private String universityName = "Tech U";
private static String universityId = "UNV-01";
// Static Nested Class
public static class Department {
private String departmentName;
public Department(String name) {
this.departmentName = name;
}
public void printInfo() {
// Can access static members of outer class
System.out.println("ID: " + universityId);
// ERROR! Cannot access instance variables of outer class!
// System.out.println(universityName);
}
}
}
public class Main {
public static void main(String[] args) {
// Notice we do NOT need to create a 'University' object first!
// We just use University as a namespace.
University.Department csDept = new University.Department("Computer Science");
csDept.printInfo();
}
}
Interview Questions
Q: When should you use a Static Nested Class instead of an Inner Class?
A: You should use a Static Nested Class by default. You should only switch to an Inner Class if your nested class absolutely must have access to the instance variables of the enclosing outer class. Static nested classes are smaller in memory (they don’t hold a hidden pointer to the outer instance) and don’t cause unintentional memory leaks.
Q: Can a Static Nested class be marked as private?
A: Yes! And this is very common. The Node class inside java.util.LinkedList is private static class Node. This completely hides the internal implementation details of the list from the outside world. Top-level classes cannot be private, but nested classes can use all access modifiers (private, protected, public).