我正在查看 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/