There are four types of nested classes in Java:
Classes defined within the body of another class (or interface) are known as nested classes.
Normally you define a class, which is a top-level class directly belonging to a package.
In contrast, nested classes
are classes contained within another class or interface.
What is the benefit of creating classes inside another class or interface?
There are several benefits.
- First, you can put related classes together as a single logical group.
- Second, nested classes can access all class members of the enclosing class, which might be useful in certain cases.
- Third, nested classes are sometimes useful for specific
purposes. For example, anonymous inner classes are useful for writing simpler event-handling code with AWT/Swing
(which is not relevant to the OCPJP 7 exam).
For now, you can believe that nested classes are useful in some situations, so it is worth learning about them.