Java 实现 - 调用 Parent class 方法来利用 Child class 数据成员

Java implementation of this - calling a Parent class method to utilizing Child class data member

此问题与 Java 中 superthis 实施决定 有关。考虑一下,

父级class包含一个变量name和一个方法getName()

public class Parent {

    protected String name = "Parent";

    protected String getName(){
        return this.name;
    }
}

而子 class 继承父 class 但有自己的 name 变量

public class Child extends Parent {

    protected String name = "Child";

    protected void printNames() {
        System.out.println("Parent: " + super.getName());
        System.out.println("Child: " + this.getName());
    }

    public static void main(String[] args) {

        Child c = new Child();
        c.printNames();
    }
}

输出:

Parent: Parent
Child: Parent

从输出中,我们可以看到:当使用 super 上下文从 Child class 调用方法 getName() 时,它 returns "Parent",但是当使用 this 上下文调用时,它再次 returns "Parent"

如果该方法只出现在Parent中class,但是具有相同访问修饰符的数据成员出现在两者中,

为什么不 this.getName() 来自 Child class return "Child" 因为它 is-a Parent 因此有 getName() 作为它的方法

更新 这个问题不是关于如何打印或覆盖 "Child",而是关于核心 Java 团队对 this 的实施决定,以及为他们准备的。

只需覆盖 Child class

中的 getName() 方法
@Override
protected String getName() {
    return name;
}

更新

如果你不想覆盖getName()方法,你可以这样做:

  • Child 构造函数中设置 name 值,因为它是一个 protected 属性
  • 不要再覆盖 Child class

    中的 name 属性
    public class Child extends Parent {
        public Child() {
            super();
            this.name = "Child";
        }
        // ...
    }
    

您需要为子项添加一个 getName() 方法 class。现在,当您调用 this.getName() 时,会调用父版本,因为它不会在子 class.

中被覆盖

字段不是overridable只有方法是,字段只能隐藏或不隐藏。 this实际上在方法Parent#getName()中引用了Parent类型的当前Object,这样就会得到Parent中定义的变量名的值或者可能是父 class 但不在子 class 中,例如 Child

这是一个简单的代码片段,展示了这个想法:

Child child = new Child();
// Show the variable name of the class Child
System.out.println(child.name);
// Show the variable name of the class Parent which is what this.name 
// does in the getName method
System.out.println(((Parent)child).name);

输出:

Child
Parent

如果你想得到 'child' 作为输出,你必须重写 getname() 方法,否则它是继承的,它将始终显示 'parent' 作为输出。