java - Java中的静态嵌套类,为什么?

标签 java class static member

我正在查看 LinkedList 的 Java 代码,并注意到它使用了静态嵌套类 Entry

public class LinkedList<E> ... {
...

 private static class Entry<E> { ... }

}

使用静态嵌套类而不是普通内部类的原因是什么?

我能想到的唯一原因是,Entry 无法访问实例变量,因此从 OOP 的角度来看,它具有更好的封装性。

但我认为可能还有其他原因,也许是性能。可能是什么?

注意。我希望我的术语是正确的,我会称它为静态内部类,但我认为这是错误的:http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html

最佳答案

您链接到的 Sun 页面在两者之间有一些关键区别:

A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class.
...

Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.

LinkedList.Entry 不需要是顶级类,因为它LinkedList 使用(还有一些其他的接口(interface)也具有名为 Entry 的静态嵌套类,例如 Map.Entry - 相同的概念)。由于它不需要访问 LinkedList 的成员,因此它是静态的是有意义的——这是一种更简洁的方法。

作为 Jon Skeet points out ,我认为如果您使用嵌套类,最好从静态开始,然后根据您的使用情况决定它是否真的需要是非静态的。

关于java - Java中的静态嵌套类,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/253492/

相关文章:

java - Android:如何告诉我的 Activity 从我的服务启动新 Activity ?

linux - 如何静态链接一个复杂的程序

java - 对象化4订单?

java - JBoss WAR部署问题(缓存问题?)

java - WebView 空引用

Matlab 类方法 : Too many arguments

c++ - 对象列表中的变量不会改变

php - 为后期静态绑定(bind)复制函数

c++ - 函数内的静态 constexpr 变量是否有意义?

动态仪器与静态仪器