Lesson 24: Nested & Inner Classes
25 Jul 2026 1 min Swarnil Singhai
Inner classes tie tightly to their enclosing instance — useful when a helper type only makes sense in the context of its outer class.
Real-time example
A LinkedList implementation defines a private Node inner class — nobody outside the list should ever construct a Node directly.
class TaskQueue {
private class Task {
String name;
Task(String name) { this.name = name; }
}
private List<Task> tasks = new ArrayList<>();
void add(String name) { tasks.add(new Task(name)); }
int size() { return tasks.size(); }
}
What's happening
Task is private to TaskQueue — it literally cannot leak outside, which is the encapsulation win of inner classes.
Use a static nested class instead if the inner type doesn't need access to the outer instance's fields.
Advertisement