我查看了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


当前回答

从http://docs.oracle.com/javase/tutorial/java/javaOO/whentouse.html:

如果需要访问,请使用非静态嵌套类(或内部类) 到封闭实例的非公共字段和方法。使用静电 嵌套类,如果您不需要此访问。

其他回答

这里有一些不明显的内存保留问题需要考虑。由于非静态内部类维护对其“外部”类的隐式引用,如果内部类的一个实例被强引用,那么外部实例也会被强引用。当外部类没有被垃圾收集时,这可能会导致一些令人费解的问题,即使看起来没有任何东西引用它。

简单的例子:

package test;

public class UpperClass {
public static class StaticInnerClass {}

public class InnerClass {}

public static void main(String[] args) {
    // works
    StaticInnerClass stat = new StaticInnerClass();
    // doesn't compile
    InnerClass inner = new InnerClass();
}
}

如果是非静态的,类不能被实例化,除非在上层类的实例中(所以在main是静态函数的例子中就不是这样)

JVM knows no nested classes. Nesting is just syntactic sugar. Below images shows Java file: Below images show class files representation of the java file : Notice that 2 class files are generated, one for parent and another for nested class. Non-static nested class' objects have access to the enclosing scope. That access to the enclosing scope is maintained by holding an implicit reference of the enclosing scope object in the nested object Nested class is a way to represent the intent that the nested class type represents a component of the parent class. public class Message { private MessageType messageType; // component of parent class public enum MessageType { SENT, RECEIVE; } } class Otherclass { public boolean isSent(Message message) { if (message.getMessageType() == MessageType.SENT) { // accessible at other places as well return true; } return false; } } private static nested class represents Point#3 & the fact the nested type can only be the subcomponent to the parent class. It can't be used separately. public class Message { private Content content; // Component of message class private static class Content { // can only be a component of message class private String body; private int sentBy; public String getBody() { return body; } public int getSentBy() { return sentBy; } } } class Message2 { private Message.Content content; // Not possible } More details here.

从http://docs.oracle.com/javase/tutorial/java/javaOO/whentouse.html:

如果需要访问,请使用非静态嵌套类(或内部类) 到封闭实例的非公共字段和方法。使用静电 嵌套类,如果您不需要此访问。

在我看来,当你看到一个内部类时,问题应该是反过来的——它真的需要是一个内部类吗?它有额外的复杂性和隐式(而不是显式和更清晰的)引用包含类的实例?

请注意,作为一个c#爱好者,我有偏见——c#没有等价的内部类,尽管它有嵌套类型。我还不能说我错过了内部类:)