Why should I use nested classes? [closed]

天涯浪子 提交于 2019-12-01 03:05:56
dd619

There are several reasons for using nested classes, among them:

  1. It is a way of logically grouping classes that are only used in one place.

  2. It increases encapsulation.

  3. Nested classes can lead to more readable and maintainable code.

  4. Child to parent class connection is simpler as it visually illustrates the variables and methods of each class.

In addition to those mentioned already, one other benefit is:

  • Nested classes also help you achieve multiple implementation inheritance (ref: Thinking in Java, page 369 - section "Why inner classes"?). As far I know, there is no other way to achieve it in Java.

According to me the one case i know when nested classes used, When we see one object(OBJ1) is tightly bind with second object(OBJ2) and we can not create first object (OBJ1) without second object(OBJ2). for an example we have employee object and one associated object is salary and we should not able to create salary object independently. because without employee to whom we are going to give salary.
Provide your feedback if i am wrong.

Second case when we are using map or map then we can use nested classes to remove map of map to make code easy to understandable.

third when we want to send data to client side and we can send it in single object having all data :)

when we need something which can define component of outer class or we want to define adapter.

I find private static classes useful when I need to pass a group of related fields into a method and manipulate the same group of data throughout a few method invocations inside a class. Similar to LinkedList.Node class which is not exposed to outside rather used to group links as a single unit.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!