【问题标题】:Why does the inherited method use not redefined variable? [duplicate]为什么继承的方法使用未重新定义的变量? [复制]
【发布时间】:2019-12-19 07:55:04
【问题描述】:

为什么 Knight 类的继承方法 show_hp() 不使用类的变量 hp,该变量是在 lower-in-hierarchy 子类中重新定义的?

我已经尝试覆盖方法 show_hp() 并且它有效,但我认为我缺少多态性的概念。

public class scratch {

    public static void main(String[] args) {
            Knight Ricardo = new Knight();
            Ricardo.show_hp();
        }


    static class Hero {
        int hp = 5;

        public void show_hp() {
            System.out.println(" I have " + hp + " hp!");
        }
    }


    static class Knight extends Hero {
        int hp = 3;
    }
}

我希望输出为 3,但实际输出为 5。

【问题讨论】:

  • 您的问题在于重新声明变量 hp。
  • 您调用的方法在Hero 类中,而不是Knight 类中。你为什么希望它打印3?字段不能像方法一样被覆盖。
  • 多态性不适用于字段,仅适用于方法。您的 Knight.hp 字段隐藏 Hero.hp 字段。它们是两个不同的领域。

标签: java oop inheritance


【解决方案1】:

Ricardo 这里是Knight 类的一个实例,具有

马力 = 3

因此,如果您希望hp 的值为5,那么您应该重写Knight 类中的一个方法,调用super 类方法。

或者,您可以避免在子类中重新声明hp 变量。

【讨论】:

    【解决方案2】:

    要实现你想要的,你需要重写 Knight 类中的 show_hp() 方法。 不需要两次声明 hp 成员。

    因为 Knight 继承了 Hero,Knight 类无论如何都会继承 hp 成员。

    多态调用适用于类的行为,这意味着它是方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-08
      • 1970-01-01
      • 1970-01-01
      • 2012-03-22
      • 2015-04-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多