采用以下代码,(source) :
class Parent {
Integer a = 1;
static Integer b = 2;
}
class Child extends Parent {
static Integer a = 41;
Integer b = 42;
}
public class Test {
public static void main(String[] args) {
Parent parent = new Parent();
Child child = new Child();
Parent yo = new Child();
System.out.format("%d %d %d %d %d %d ",
parent.a,
parent.b,
child.a,
child.b,
yo.a,
yo.b);
}
}
为什么yo.a
和yo.b
的结果分别是1和2?我很困惑,因为 yo
指向一个 Child
对象,结果会产生 41 和 2,因为在 Parent
中,a 是非-static,因此将打印子类版本的 a
而不是父类(super class)版本。
最佳答案
变量(字段)不会被覆盖,既不是实例变量也不是类变量。
一个对象总是拥有来自所有父类(super class)的所有实例变量。一个类只有它自己定义的静态变量,尽管它也可以访问父类(super class)(和接口(interface))的变量(如果不是私有(private)的)。
如果您在子类中重新定义一个变量,您将隐藏原始变量,即不能直接访问它。它仍然存在。
哪个变量可以访问仅取决于用于访问它的(编译时)类型,而不取决于具体对象的类。
关于java - 有关混合重写声明变量和实例变量的问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6267909/