静态变量及其值的继承是如何工作的?

How does the inheritance of static variables and their values work?

我有这段代码,我的问题是,静态变量z的值是否在子类中是"shared"?具体:当我声明 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一个?

我很困惑。希望有人能给我解释一下。

if the value of the static variable z is "shared" among the subclass(es)?

是的。 static 变量是 class 级变量,这意味着它们不属于 class 的实例,而是属于 class 本身。只要它们未被声明为私有且不被继承,它们就可以从子 class 访问。 class 的所有实例只有一个 static 变量,无论它是 class 本身的实例还是它的任何子 class 的实例。因此:

A.z = 5; // z is 5 now
B.z = 7; // z is 7 now 
System.out.prinln(A.z); // will print 7 since there's only one z shared by everybody
                        // remember, z belongs to A not to an instance of A.

When I declare b does this mean that first the constructor of A is used and passes the modified values of z to the constructor of B?

不完全是。在构造子 class 之前,需要构造其父 class。你怎么能扩展不存在的东西=]?因此,在子构造函数中的任何其他指令之前调用父构造函数。

public B() {
    x++;
    z++
}

等同于

public B() {
    super(); // initialize A before initializing B
    x++;
    z++
}

如果您没有显式调用 super(),除非您需要将某些东西传递给父构造函数,否则编译器将为您插入 super()。因此,在 B 构造函数中,调用了 A 的构造函数,但它不会将 z 传递给 B 它只是执行您指示它执行的操作并继续前进。