静的とは、オブジェクトごとではなく、クラスごとに 1 つあることを意味します。これは、メソッドと変数の両方に当てはまります。
静的フィールドは、そのクラスのオブジェクトがいくつ作成されても、そのようなフィールドが 1 つあることを意味します。Java でクラス変数をオーバーライドする方法はありますか? をご覧ください。静的フィールドのオーバーライドの問題について。つまり、静的フィールドはオーバーライドできません。
このことを考慮:
public class Parent {
static int key = 3;
public void getKey() {
System.out.println("I am in " + this.getClass() + " and my key is " + key);
}
}
public class Child extends Parent {
static int key = 33;
public static void main(String[] args) {
Parent x = new Parent();
x.getKey();
Child y = new Child();
y.getKey();
Parent z = new Child();
z.getKey();
}
}
I am in class tools.Parent and my key is 3
I am in class tools.Child and my key is 3
I am in class tools.Child and my key is 3
Key が 33 に戻ることはありません。ただし、getKey をオーバーライドしてこれを Child に追加すると、結果が異なります。
@Override public void getKey() {
System.out.println("I am in " + this.getClass() + " and my key is " + key);
}
I am in class tools.Parent and my key is 3
I am in class tools.Child and my key is 33
I am in class tools.Child and my key is 33
getKey メソッドをオーバーライドすることで、Child の静的キーにアクセスできます。