【发布时间】: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