Java 内部类访问和最佳实践

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19825956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 20:31:17  来源:igfitidea点击:

Java Inner Class Access and Best Practices

javaoopinner-classes

提问by DanK

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. 外部类是否可以访问内部类中的私有变量和方法?

  2. 我看过一些文章提到内部类应该是私有的,这样它们只能被外部类访问。这对内部类的可访问性有什么影响?

  3. 当涉及到您的内部类时,处理访问级别的最佳实践是什么?我假设封装越多越好,但这是否以牺牲可访问性为代价?

采纳答案by jaco0646

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

Effective Java(第 2 版)第 22 条:“优先使用静态成员类而不是非静态成员”详细介绍了该主题。

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 staticby default. To get technical, Effective Java calls these static member classes, as opposed to inner classes, and uses the term nested classto 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."
  1. 内部类不应访问外部类实例,除非需要访问,即static默认情况下应该是内部类。从技术上讲,Effective Java 将这些静态成员类称为静态成员类,而不是内部类,并使用术语嵌套类来包含静态和非静态版本。
  2. 外部类始终可以访问其内部类的成员,即使这些成员是private. 这样,内部类只能向其外部类公开自己。
  3. “内部类应该只存在为它的外部类服务。”

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 publicinner classes are perfectly acceptable. There are many examples in Java, such as AbstractMap.SimpleEntry.

就个人而言,我倾向于在允许内部类的构造函数为 时实现内部类private,即当一个类只能从另一个(外部)类实例化时。任何额外的封装,例如制作整个内部类private,都是可取的;但public内部类是完全可以接受的。Java 中有很多例子,例如AbstractMap.SimpleEntry.