静态意味着每个类有一个,而不是每个对象一个。对于方法和变量都是如此。
静态字段意味着存在一个这样的字段,无论创建了多少该类的对象。请看一下有没有办法在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 的静态密钥。