public class Artifact {
public int value = 0;
public static class Goblet extends Artifact {
public Goblet() {
super();
value = 5;
}
public void modifyOuterClassfield(int someValue) {
value = 100 + someValue;
}
}
public static class Coin extends Artifact {
public Coin() {
super();
value = 10;
}
public void modifyOuterClassfield(int someValue) {
value = 100 + someValue;
}
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public static void main(String[] args) {
Artifact a = new Coin();
Artifact b = new Goblet();
Coin c = new Coin();
Artifact d = new Artifact();
System.out.println(a.getValue());
System.out.println(b.value);
System.out.println(c.getValue());
System.out.println(d.getValue());
a.value = 101;
b.value = 202;
c.setValue(303);
d.setValue(404);
System.out.println(a.getValue());
System.out.println(b.value);
System.out.println(c.value);
System.out.println(d.getValue());
}
}
输出:
10
5
10
0
101
202
303
404
静态类与静态变量不同。因此,实例初始化会起作用,因为编译器不会抱怨,但这不是完整的画面,因为您可以以其他方式初始化变量,除非您的内部类是匿名内部类,因为匿名内部类不能有构造函数。
只要字段未声明为私有,外部类的字段在内部类中始终可见!
http://www.javaworld.com/javaqa/1999-08/01-qa-static2.html
http://www.artima.com/designtechniques/initializationP.html