Why should I use nested classes? [closed]

2019-02-16 07:02发布

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?

4条回答
兄弟一词,经得起流年.
2楼-- · 2019-02-16 07:49

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楼-- · 2019-02-16 07:54

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楼-- · 2019-02-16 07:56

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.

查看更多
Juvenile、少年°
5楼-- · 2019-02-16 08:04

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.

查看更多
登录 后发表回答