對不起Java的新手可能沒有描述它非常正確。創建基於文本的冒險試圖調用超類方法,但傳遞子類的參數?
基本上我有一個名爲GameCharacter的超類。兩個亞類Player和Monster。怪物有四個子類Ork,Troll,Goblin和Boss
我有一個抽象方法叫做takeTurn(),在超類中找到。我在子類中有充實的方法。所以當涉及到輪流調用時,我怎麼知道它會訪問正確的子類?
我的超類
public abstract class GameCharacter{
public abstract String getName();
public abstract int getHealth();
public abstract int getAttackPower();
protected String gameCharacterName;
protected int gameCharacterHealth;
protected int gameCharacterAttack;
public GameCharacter(String name, int health, int attack){
this.gameCharacterName = name;
this.gameCharacterHealth = health;
this.gameCharacterAttack = attack;
}
public abstract void takeTurn(GameCharacter character);
我採取的方法依次
public static void runCombatLoop(Monster monster){
while (isPlayerAlive()&& isMonsterAlive(monster))
{
GameCharacter player = new Player();
Monster enemy = new Monster(){};
enemy.Monster();
GameCharacter.takeTurn(player);
GameCharacter.takeTurn(enemy);
}
}// run combat loop end
'takeTurn'不是'static',你必須在'GameCharacter'的實例上調用它,它不應該是'player.takeTurn',但是,我不知道爲什麼你會傳遞另一個'GameCharacter 「對它? – MadProgrammer
查看java的繼承主題 – Ahmed
該代碼無法編譯 –