这个问题的灵感来自 this other one我偶然发现。
给出以下代码:
public class Test {
public static void main(String[] args) {
Derived b = new Derived();
Base a = b;
System.out.println("b.i -> " + b.i);
System.out.println("a.i -> " + a.i);
System.out.println("b.getI() -> " + b.getI());
System.out.println("a.getI() -> " + a.getI());
}
}
class Base {
int i = 1;
public int getI() {
return i;
}
}
class Derived extends Base {
int i = 2;
public int getI() {
return -i;
}
}
// Output:
// b.i -> 2
// a.i -> 1
// b.getI() -> -2
// a.getI() -> -2
有人可以解释为什么a.i
返回1
吗?它不应该访问 Derived
类中的 i
字段吗?
另外,在调试代码时,我可以看到这样的内容:
在那里您可以看到 Derived
类正在存储对 Base.i
的引用。
为什么会发生这种情况? Base.i
不应该被 Derived.i
继承并覆盖吗?
最佳答案
您已经了解了 Java 中称为变量隐藏的功能。
Derived
中的字段“i”隐藏了 Base
类中的字段“i”。
与方法不同,这些字段在 java 中不能被覆盖,因此存在这种行为。
我找到了一个非常深入的tutorial关于您可能认为有用的主题
关于Java 字段继承和向上转型的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61436312/