Search⌘ K
AI Features

Inner and Nested Classes

Explore different types of nested classes in Java, including static nested, member inner, local, and anonymous classes. Understand how to leverage these structures to enhance code organization, encapsulate logic, and maintain clean class hierarchies in advanced object-oriented programming.

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 ...