静态与非静态嵌套类
在创建嵌套类时,你可以选择将嵌套类设置为 static:
public class OuterClass1 {
private static class StaticNestedClass {
}
}
或非静态:
public class OuterClass2 {
private class NestedClass {
}
}
从本质上讲,静态嵌套类没有 ***** 外部类的周围*实例,而非静态嵌套类则具有。这会影响允许实例化嵌套类的位置和时间,以及允许这些嵌套类的哪些实例访问。添加到上面的示例:
public class OuterClass1 {
private int aField;
public void aMethod(){}
private static class StaticNestedClass {
private int innerField;
private StaticNestedClass() {
innerField = aField; //Illegal, can't access aField from static context
aMethod(); //Illegal, can't call aMethod from static context
}
private StaticNestedClass(OuterClass1 instance) {
innerField = instance.aField; //Legal
}
}
public static void aStaticMethod() {
StaticNestedClass s = new StaticNestedClass(); //Legal, able to construct in static context
//Do stuff involving s...
}
}
public class OuterClass2 {
private int aField;
public void aMethod() {}
private class NestedClass {
private int innerField;
private NestedClass() {
innerField = aField; //Legal
aMethod(); //Legal
}
}
public void aNonStaticMethod() {
NestedClass s = new NestedClass(); //Legal
}
public static void aStaticMethod() {
NestedClass s = new NestedClass(); //Illegal. Can't construct without surrounding OuterClass2 instance.
//As this is a static context, there is no surrounding OuterClass2 instance
}
}
因此,你对静态与非静态的决定主要取决于你是否需要能够直接访问外部类的字段和方法,尽管它也会影响你何时何地构造嵌套类。
根据经验,除非你需要访问外部类的字段和方法,否则请将嵌套类设置为静态。与将字段设为私有类似,除非你需要公开,这会降低嵌套类可用的可见性(通过不允许访问外部实例),从而降低出错的可能性。