我创建了一个测试项目,但我遇到了一些我找不到的东西。Java调用构造函数
我想在FightManager中调用怪物。我想Monster的变量(name
,health
,damage
和defense
)任何怪物是随机的(WolfMonster
或GoblinMonster
)
以前我只有一个怪物等于,我设法做到这一点,但现在,当有2个怪物如果选择不同的怪物,我怎样才能将变量传递给另一个值?
public class Units {
int health;
int damage;
int defense;
String name;
public boolean isAlive(){
if(health >= 1){
return true;
}else{
return false;
}
}
}
public class Monster extends Units{
public Monster(String name,int health,int damage,int defense){
this.name = name;
this.health = health;
this.damage = damage;
this.defense = defense;
}
}
public class GoblinMonster extends Monster {
public GoblinMonster(String name, int health, int damage, int defense) {
super("Goblin",50,5,6);
this.name = name;
this.health = health;
this.damage = damage;
this.defense = defense;
}
}
public class WolfMonster extends Monster {
public WolfMonster(String name, int health, int damage, int defense) {
super("Wolf",50,5,6);
this.name = name;
this.health = health;
this.damage = damage;
this.defense = defense;
}
}
public class FightManager {
GameManager manage = new GameManager();
Player player = new Player("Player",100,10,5);
GoblinMonster gobli = new GoblinMonster("Goblin", 40, 7, 4);
WolfMonster wolf = new WolfMonster("Wolf",50,9,6);
boolean myTurn = true;
....
我想知道如何根据生成的怪物来分配一个怪物值。
目前尚不清楚你在询问什么。你能指定一下你的意思吗? –
我没有看到任何需要这里的两个子类。他们有完全相同的字段和相同的行为(没有重写的方法)。而且,你的构造函数没有意义。您正在初始化每个字段两次:一次在基础构造函数中,再次在子类构造函数中。你从子类的构造函数传递一个硬编码的名字,但是用传入的名字立即覆盖它。 –
不确定是什么问题。看起来你对[多态行为]感到困惑(https://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html)。 –