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 are the Situations in Which You Choose HashSet or TreeSet in ...

What is the Difference Between DOM and SAX Parser in Java ?

Replacing Hashtable With ConcurrentHashMap in Java

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

How Can You Make an Object Eligible for Garbage Collection in Jav ...