静的とは、オブジェクトごとに1つではなく、クラスごとに1つ存在することを意味します。これはメソッドと変数の両方に当てはまります。
静的なフィールドは、そのクラスのオブジェクトがいくつ作成されても、そのようなフィールドが1つあることを意味します。静的フィールドのオーバーライドについては、Is there a way to override class variables in 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
キーは、あなたがのgetKeyをオーバーライドして、子供にこれを追加した場合、その結果は異なるだろう、しかしバック33のように来ることはありません。 getKeyメソッドをオーバーライドすることで
@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
、あなたは子供の静的なキーにアクセスすることができます。 「 「はthis.getClass()」と警告を使用することはできません。今、注目すべき
public static void getKey() {
System.out.println("I am in and my key is " + key);
}
2つのこと:rajah9の答えで