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


当前回答

首先,非静态内部类有一个额外的隐藏字段,指向外部类的实例。因此,如果Entry类不是静态的,那么除了拥有它不需要的访问之外,它将携带四个而不是三个指针。

作为一个规则,我想说,如果你定义了一个类,基本上是作为数据成员的集合,就像C中的“struct”,考虑让它静态。

其他回答

内部类的优势——

一次性使用 支持和改进封装 readibility 私有字段访问

没有外部类的存在,内部类就不存在。

class car{
    class wheel{

    }
}

内部类有四种类型。

正常的内部类 局部内部类 匿名内部类 静态内部类

点——

from static inner class ,we can only access static member of outer class. Inside inner class we cananot declare static member . inorder to invoke normal inner class in static area of outer class. Outer 0=new Outer(); Outer.Inner i= O.new Inner(); inorder to invoke normal inner class in instance area of outer class. Inner i=new Inner(); inorder to invoke normal inner class in outside of outer class. Outer 0=new Outer(); Outer.Inner i= O.new Inner(); inside Inner class This pointer to inner class. this.member-current inner class outerclassname.this--outer class for inner class applicable modifier is -- public,default, final,abstract,strictfp,+private,protected,static outer$inner is the name of inner class name. inner class inside instance method then we can acess static and instance field of outer class.

10.内部类在静态方法中,那么我们只能访问的静态字段

外部类。

class outer{

    int x=10;
    static int y-20;

    public void m1() {
        int i=30;
        final j=40;

        class inner{

            public void m2() {
                // have accees x,y and j
            }
        }
    }
}

首先,非静态内部类有一个额外的隐藏字段,指向外部类的实例。因此,如果Entry类不是静态的,那么除了拥有它不需要的访问之外,它将携带四个而不是三个指针。

作为一个规则,我想说,如果你定义了一个类,基本上是作为数据成员的集合,就像C中的“struct”,考虑让它静态。

使用静态嵌套类而不是非静态类在某些情况下可以节省空间。例如:在一个类中实现一个比较器,比如Student。

public class Student {
  public static final Comparator<Student> BY_NAME = new ByName();
  private final String name;
  ...
  private static class ByName implements Comparator<Student> {
    public int compare() {...}
  }
}

然后静态确保Student类只有一个Comparator,而不是每次创建新的Student实例时都实例化一个新的Comparator。

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

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

静态与普通的原因之一与类加载有关。不能在其父类的构造函数中实例化内部类。

PS:我一直认为“嵌套”和“内部”是可以互换的。术语之间可能有细微的差别,但大多数Java开发人员都能理解。