我有這段代碼,我的問題是,靜態(tài)變量z的值是否在子類之間“共享”?具體:當(dāng)我聲明時(shí)b,這是否意味著首先使用A的構(gòu)造函數(shù)并將z的修改后的值傳遞給B的構(gòu)造函數(shù)?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這些值是否因?yàn)閦是靜態(tài)的而傳遞給子類,是否意味著如果我不更改z的值(如果我不通過在A中傳遞另一個(gè)具體值來更改z)的話,它們將在運(yùn)行代碼時(shí)被更改?我很困惑。希望有人可以向我解釋。
添加回答
舉報(bào)
0/150
提交
取消