【发布时间】:2017-05-08 16:03:57
【问题描述】:
我创建了一个测试项目,但遇到了一些我想不通的问题。
我正在尝试在 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;
....
我想知道如何根据生成的怪物来分配怪物的值。
【问题讨论】:
-
不清楚你在问什么。你能具体说明一下你的价值是什么意思吗?
-
我认为这里不需要两个子类。它们具有完全相同的字段和相同的行为(没有被覆盖的方法)。此外,您的构造函数没有任何意义。您将每个字段初始化两次:一次在基构造函数中,另一次在子类构造函数中。你从子类构造函数中传递了一个硬编码的名称,但在之后立即用传递的名称覆盖它。
-
不确定是什么问题。看来你对polymorphic behaviors感到困惑。
-
您当前的代码确实需要继承。您所有的“特殊”单位仅在属性上有所不同。但是应该使用继承来提供不同的行为,这意味着:方法具有相同的名称但不同的内容。
标签: java constructor call