Nested Class in JAVA
Inner classes and anonymous classes are cool . Actually, I’d prefer anonymous
functions, as most of the things I write in-place are implementations of one-function
interfaces like Runnable.
Benefit of using nested class
Among several compelling reasons for using nested classes, the most common
advantage of it that I see is the logical and systematic grouping of classes .If a class
is used only in one other top level class then it will be a good programming approach
to make that class a nested class in the top level class. In this way we will avoid the
pointless extra task of creating a separate class in a separate java file and then using
it, instead we can use it directly inside a top level class. Nesting such â€œhelper classesâ€
make their package more streamlined.
Another reason is the better readability and maintainable code, nesting small classes
within top-level classes places the code closer to where it is used and arranges all the
method of the nested class right inside a single top class in a collective data form inside
the nested class, which otherwise would be scattered throughout the body of top level
or enclosing class.
Increased encapsulation â€“ nested classes are treated similar to other members of the
enclosing class and hence we can use access modifiers (private , public ,package
or protected) .Considering two top-level classes, A and B ,where B needs access to
members of A that would otherwise be declared private. By hiding class B within class
A, Aâ€™s members can be declared private and B can access them. In addition, B itself
can be hidden from the outside world. This also facilitates “shared scope” i.e. variables
can be used across classes instead of declaring them again and again for separate
Yet another use comes when we need to extend more than one classes in a single
class because only one class can be extended by a given class. In these cases nested
classes are used as they can also inherit the methods of a single class. So in this way
we can inherit methods of more than one class in a single top level class using the
concept of nested class.
How to identify nested class by its name
The class formed by compiling java file using nested classes contains the name of
top level class as well as the name of the nested class like let the name of class be
MyClass and name of the nested class be WindowCloser class , then name of class file
will be MyClass$WindowCloser.class .