你可以做到static
。static
字段在实例之间共享;如果您更改子类中的一个静态变量,则父亲,因此,之后创建的所有子类的实例将共享更改的值。
考虑这些类:
父亲.java
class Father {
protected static int i;
public Father() {
System.out.println("Father: " + i);
}
}
Child.java:
class Child extends Father {
public Child() {
i = 4;
System.out.println("Child: i: " + i);
System.out.println("Child: this.i: " + this.i);
System.out.println("Child: super i: " + super.i);
}
}
女儿.java:
public class Daughter extends Father {
public Daughter() {
System.out.println("Daughter: i: " + Daughter.i);
}
}
主.java:
class Main {
public static void main(String[] args) {
System.out.println("First daughter");
Daughter daughter = new Daughter();
Father father = new Father();
Child child = new Child();
System.out.println("Second daughter");
Daughter daughter2 = new Daughter();
}
}
输出:
First daughter
Father: 0
Daughter: i: 0
Father: 0
Father: 0
Child: i: 4
Child: this.i: 4
Child: super i: 4
Second daughter
Father: 4
Daughter: i: 4