Answer: not static at all. A static inner class behaves like a normal class except that it is in the namespace of the outer class (“for packaging convenience”, as the official Java tutorial puts it).
因此,例如:
public class Outer {
private int x = 0;
static class Inner {
//...
}
}
与真正的内部(嵌套)类相反,您不需要Outer实例即可创建Inner实例:
Outer.Inner inner = new Outer.Inner();
内部实例对外部实例没有特殊知识。 内部类的行为就像顶级类一样,只需将其限定为“ Outer.Inner”即可。
Why I am writing about this?
因为令我震惊的是,我的两个同事(都是经验丰富的Java开发人员)不确定静态内部类是否与静态成员有关,因此不确定全局状态。
也许他们不使用静态内部类。
When do I use static inner classes?
我使用静态内部类
- 当它仅用于外部类并且独立于外部类的(私有)成员时,当它在概念上与外部类(例如Builder类)联系在一起时为了包装方便。
通常,静态内部类的可见性不是公开的。 在这种情况下,无论是在同一源文件中创建静态内部类还是顶层类都没有太大区别。 因此,第一个代码示例的替代方法是:
public class Outer {
// ...
}
// not really inner any more
class Inner {
// ...
}
(2)的示例是一个Builder类:
public class Thing {
//...
public static class Builder {
// ... many withXXX methods
public Thing make() // ...
}
}
如果内部实例需要访问外部实例的(私有)成员,则内部需要是非静态的。