为什么对象的类型是child时,使用parent变量的值而不是child变量的值?

Why the value of parent variable is used instead of value of child variable when the type of the object is child?

public class Parent {

    String name = "parent";

    public static class Child extends Parent {
        String name = "child";
    }

    public static void main(String[] args) {
        Parent p = new Child();
        Child c = new Child();
        System.out.println(p.name);   //parent
        System.out.println(c.name);   //child
    }
}

有一个规则,对象的类型定义了哪些属性存在于内存中。 所以我的问题是为什么 p.name 的输出是 'parent' 而不是 'child' 当 p 对象的类型是 Child?

why the output of the p.name is 'parent' but not 'child' when the type of the p object is Child?

因为ovverriding/polymorphism只适用于方法。变量仍然绑定到它的类型。在您的情况下,类型是 Parent,因此您会看到来自 Parent 的变量。

因为在子 class 中定义同名字段不会覆盖父 class 中的字段。

方法是可覆盖的,字段不是。

此处p.name指的是Parent声明类型的name

    Parent p = new Child();
    Child c = new Child();
    System.out.println(p.name);   //parent