Search⌘ K
AI Features

Inner and Nested Classes

Learn how to use Java inner and nested classes to keep related logic together while enhancing encapsulation and code readability. Understand static nested classes, member inner classes, local classes, and anonymous classes to choose the best approach for modular and maintainable Java applications.

As our applications grow, we often find ourselves creating small helper classes that are used by only one other class. If we place every single helper in its own file, our package structure becomes cluttered and hard to navigate.

Java solves this by allowing us to define a class inside another class. This powerful feature helps us keep related logic together, hide implementation details, and write cleaner, more organized code.

The terminology here is precise:

  • Nested class: The general term for any class defined inside another.

  • Static nested class: A nested class declared with static.

  • Inner class: A nested class without static (including member, local, and anonymous classes).

Why nest classes?

Before we look at the syntax, let’s understand why we would choose to nest a class rather than giving it its own file.

  • Logical grouping: If a class like Cache is useful only to a CPU class, it makes sense to keep them together physically in the source code.

  • Increased encapsulation: A nested class can access ...