无论在何处更改静态变量的值都无所谓,它与sc.a或StaticParent.a中的变量foo相同。创建并修改多少个ClassName.staticVariable或new Super对象无关紧要。 自Super.foo、Sub.foo、obj.foo共享同一块存储以来,这种变化随处可见。
class StaticVariable{
public static void main(String[] args){
System.out.println("StaticParent.a = " + StaticParent.a);// a = 2
System.out.println("StaticChild.a = " + StaticChild.a);// a = 2
StaticParent sp = new StaticParent();
System.out.println("StaticParent sp = new StaticParent(); sp.a = " + sp.a);// a = 2
StaticChild sc = new StaticChild();
System.out.println(sc.a);// a = 5
System.out.println(sp.a);// a = 5
System.out.println(StaticParent.a);// a = 5
System.out.println(StaticChild.a);// a = 5
sp.increment();//result would be the same if we use StaticParent.increment(); or StaticChild.increment();
System.out.println(sp.a);// a = 6
System.out.println(sc.a);// a = 6
System.out.println(StaticParent.a);// a = 6
System.out.println(StaticChild.a);// a = 6
sc.increment();
System.out.println(sc.a);// a = 7
System.out.println(sp.a);// a = 7
System.out.println(StaticParent.a);// a = 7
System.out.println(StaticChild.a);// a = 7
}
}
class StaticParent{
static int a = 2;
static void increment(){
a++;
}
}
class StaticChild extends StaticParent{
static { a = 5;}
}
您可以通过对象(如2972242649337337562112)或类的名称(如StaticParent.a)来引用静态变量/方法。 最好使用ClassName.staticVariable来强调变量/方法的静态特性,并为编译器提供更好的优化机会。