Why Do We Use Nested Classes in Java ?

There are following reasons for using nested classes...

Encapsulation : Nested classes increase encapsulation. Let say there are two top-level classes, Foo and Bar. Bar needs access to private members of Foo. We can hide class Bar within class Foo. In this way, private members of Foo can be accessed by class Bar. So class Foo remains encapsulated. Also, class Bar remains hidden from the outside world.

Code Clarity : Nested classed make the code more readable and well organized. Only Top-level classes are exposed. The helper classes are kept hidden and closer the code where it is used by a Top-level class.

Logical Grouping : We can logically group classes in one place. If one class is useful to only one other class, then we put smaller class within the larger class and keep them in one file. This kind of nesting "helper classes" in a toplevel class makes the package more streamlined.



You May Interest

How Can We Find the Memory Usage of JVM From Java Code ?

Comparing HashSet and TreeSet Collections in Java

Java How To Find The Average Of 10 Numbers Using A While Loop

What are the Different Types of Events Provided by Spring Framewo ...

How Can We Analyze the Dependencies in Java Classes and Packages ...