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

What is the Purpose of Properties File in Java ?

How Will You Create a Shallow Copy of a Map in Java ?

What is the Importance of hashCode and equals Methods in Java ?

What are the Differences Between Comparable and Comparator in Jav ...

How Will You Handle InterruptedException in Java ?