In object-oriented programming (OOP), a nested class is a class that is completely contained within another class. A variety of computer languages have support for this object-oriented structure, including C++ and the Java programming language. If a nested class is not declared static, it can also be called an inner class. A class can contain any number of inner classes, and each inner class can also contain inner classes of its own. Nested classes can be very useful, but they can also make class structures complicated quickly, so it is best for them to be used as part of a careful plan so that they don’t become needlessly complex.
A nested class is often helpful to encapsulate small groups of functions or variables that are useful to another specific class. For example, if class A contains a group of methods that only it uses, these methods can be grouped into inner class B. Methods inside the inner class have access to the outer class’s variables and methods while maintaining their own variables or constants as necessary. A nested class can be used as either a functional or organizational construct; while it is useful to encapsulate functionality, it is equally useful as an organizational tool. Ideal use of inner classes will both group together related functionality and organize code for easier readability and comprehension.
Commenting should be done on a nested class just as it is done on the outer class; it is easy for beginners to confuse inner classes with methods and forget this. When commenting a nested class, it is best for it to be thought of as a top-level class and to comment it accordingly. Inner class comments also provide an opportunity for the programmer to clarify the inner class’s functionality and the rationale behind its organizational scheme. Multiple inner classes can exist within one outer class, so it is especially important for the programmer to comment each one clearly.
If a nested class is not declared static, an instance of the outer class must be explicitly created before an instance of the inner class is created. For inner classes that are declared static, this is not true. A static nested class usually can be created with fewer keystrokes and might have a wider scope than a simple inner class, so static nested classes are useful for creating easy to access utility methods, such as factories or simple self-contained methods with wide applications.
It is often helpful to developers when nested classes are described using the Unified Modeling Language. The Unified Modeling Language annotates and illustrates class structure and behavior in an unambiguous fashion, often using diagrams. Nested classes are given independent descriptions from the outer classes in which they reside, so it is very easy for their functionality to be identified and analyzed. Although it is not required for a nested class to be annotated in this way, it is often better for programmers to err on the side of greater detail.