Why Use Nested Classes?
by, 04-26-2012 at 05:57 PM (510 Views)
Many compelling reasons are present to use the nested classes. Among them:
- Grouping of classes is done logically which are just used at 1 place.
- Encapsulation is increased
- Nested classes might be leading to more maintainable & readable code.
Logical classes groupings—When one class is useful towards just 1 class, it would be so logical to do its embedding in that particular class so that to keep them together. They are known as the helper classes whose nesting will be making a package much more stream lined.
Enhanced encapsulation—Let us consider 2 top level classes i.e A & B. B wants to access the members of A, which will be declared to be private otherwise. Hide class B in Class A so to declare A’s members to be private & can be accessed by B. Additionally, B can hide from outer world.
More maintainable and readable code—Nest smaller classes in top-level classes that would place the code close, to where this shall be used.