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 Singleton Class in Java ?

What are the Advantages of Multithreading in Java ?

How Will You Define the Scope of a Bean in Spring ?

What are the Situations in Which You Choose HashSet or TreeSet in ...

How Will You Use a Cookie in JSP ?