我有这段代码,我的问题是,静态变量z的值是否在子类之间“共享”?具体:当我声明时b,这是否意味着首先使用A的构造函数并将z的修改后的值传递给B的构造函数?
public class Test {
public static void main(String[] args){
A a = new A();
System.out.println("A: " + a.x);
a.print();
A b = new B();
System.out.println("B: " + b.x);
a.print();
}
}
public class A {
public static int z; // default: 0
public int x = 10;
public A() {
x++;
z++; // z = 1
}
print(){
System.out.println("A: "+ x);
System.out.println("A: "+ ++z); // z = 2
}
}
public class B extends A {
public int x = 100;
public B() {
x++;
z++; //z is not 3. z = 4 (because of the constructor of A that
uses the modified values of z?)
}
public void print() {
System.out.println("B: "+ x);
System.out.println("B: "+ ++z); // z = 5
}
}
输出为:
A:11 A:11 A:2 B:11 B:102 B:5
这些值是否因为z是静态的而传递给子类,是否意味着如果我不更改z的值(如果我不通过在A中传递另一个具体值来更改z)的话,它们将在运行代码时被更改?
我很困惑。希望有人可以向我解释。
相关分类