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 a Filter in JSP ?

What are the Different States of a Thread in Java ?

What are the Differences Between a Vector and an ArrayList in Jav ...

How Can You Upload a Large File in JSP ?

Why Do We Use Static Initializers in Java ?