我正在尝试编写简单的游戏来测试Java中的一些新功能。我有职业怪物,并且有 int hp:
public class Monsters {
int hp;
public Monsters() {
}
public Monsters(int hp) {
this.hp = hp;
}
}
然后我有两个子类 - 一个主要英雄 HERO,和他的对手恶魔。他们也有 int hp,因为他们的生活水平不同:
public class Devil extends Monsters {
int hp = 200;
}
和英雄:
public class HERO extends Monsters{
public HERO(int hp) {
this.hp = hp;
}
}
我正在尝试编写 fight(); 方法:
public void fight(Monsters hero) {
int heroLife = hero.hp;
int opLife = hp;
System.out.println(opLife + " - Devil's lifen"
+ heroLife + " - Hero's life");
}
好的,现在在main()类游戏中,我正在测试他们的hp:
public class Gra {
public static void main(String[] args) {
HERO hero = new HERO(5);
Devil devil = new Devil();
devil.fight(hero);
}
}
这是我的输出:
0 - Devil's life
5 - Hero's life
为什么是 0,而不是 200?
类和Devil
类中都有一个hp
变量Monsters
。当您从Monsters
类的方法(您的filght
方法)访问hp
时,您将获得变量 hp
,默认情况下为 0。
你应该只在基类中hp
,并使用Monster
的构造函数来正确初始化它:
例如:
public class Devil extends Monsters
{
public Devil ()
{
super(200);
}
}
问题
您正在创建新的hp
字段并隐藏继承的hp
。
溶液
取代
public class Devil extends Monsters {
int hp = 200;
}
跟
public class Devil extends Monsters {
public Devil() {
this.hp = 200;
}
}
祝你好运。
你没有在你的魔鬼类中定义默认构造函数。首先使用超级关键字在默认构造函数中实现默认构造函数。
public class Devil extends Monsters
{
public Devil() {
super();
this.hp = 200;
}
}