Java Inner Class Access and Best Practices

偶尔善良 提交于 2019-12-21 07:56:17

问题


I know that an inner class has access to everything in the outer class (because it's a member of that class) but what about the other way around?

  1. Does the outer class have access to private variables and methods within an inner class?

  2. I've seen articles mentioning that inner classes should be private so that they are accessible only to the outer class. What does that do to the accessibility of that inner class?

  3. What is best practices in dealing with access levels when it comes to your inner classes? I'm assuming more encapsulation the better but does that come at the expense of accessibility?


回答1:


This topic is covered in some detail by Effective Java (2nd edition) Item 22: "Favor static member classes over nonstatic".

A brief summary:

  1. An inner class should not have access to an outer class instance, unless that access is required, i.e. inner classes should be static by default. To get technical, Effective Java calls these static member classes, as opposed to inner classes, and uses the term nested class to encompass both the static and nonstatic versions.
  2. An outer class always has access to the members of its inner classes, even when those members are private. In this way, an inner class can expose itself only to its outer class.
  3. "An inner class should exist only to serve its outer class."

Personally, I'm inclined to implement an inner class whenever doing so allows the inner class's constructors to be private, i.e. when a class can only be instantiated from one other (outer) class. Any additional encapsulation, such as making the entire inner class private, is desirable; but public inner classes are perfectly acceptable. There are many examples in Java, such as AbstractMap.SimpleEntry.



来源:https://stackoverflow.com/questions/19825956/java-inner-class-access-and-best-practices

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