为什么更改类型会导致成​​员的不同用法?

Why does changing the type lead to different usage of members?

所以我正在测试一些代码片段以围绕继承的概念进行测试,当我遇到这个 - 对我来说 - 奇怪的现象时。

首先我测试了这个简单的代码:

public class Main{
    public static void main(String[] args) {
        Bar bar = new Bar();

        System.out.println("age = " + bar.age);

        bar.test();
    }
}

class Foo{
    int age = 2;

    void test(){
        System.out.println("TEST FOO");
    }
}

class Bar extends Foo{
    int age = 4;

    void test(){
        System.out.println("TEST BAR");
    }
}

输出如我所料:

age = 4
TEST BAR

然后我对第 3 行做了一个小改动,我将类型 Bar 更改为 Foo,如下所示:

Foo bar = new Bar();

现在当我 运行 代码时,它给了我一个我认为很奇怪的输出:

age = 2
TEST BAR

为什么代码 bar.age 现在正在使用 Foo class 的 age 成员(这是有道理的),而 bar.test(); 仍然使用 Bar class 的方法(而不是来自 Foo 的方法,因为那是类型)?

Barage 阴影Fooage.

此外,字段不是多态的(参见函数)。

所以写Foo bar = new Bar();时,访问age字段时使用barstatic类型,到return 2. bardynamic 类型用于决定调用 test() 的哪个覆盖,即 Bar 类型。

因为您定义了两个不同的年龄字段,每个 class。字段未被覆盖。