我創建了一個測試項目,但我遇到了一些我找不到的東西。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)。 –