Why should I use nested classes? [closed]

2019-02-16 07:15发布

问题:

When is it feasible to nest classes? The most common advantage of it that I see is "shared scope" (use of variables across classes).

Is this less attractive/less a best practice than just putting the nested class in it's own file, and passing the arguments through the Constructor?

回答1:

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.



回答2:

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.


回答3:

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.



回答4:

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.