好吧,這已經有一段時間了,但我正在考慮重新編程。從它自己的類中取出變量數據,而不是它的子類,即使從子類中調用
無論如何,即使從子類調用,此代碼也會從它自己的類中取得變量數據,而不是它的子類。我如何得到它,因此它在兒童調用時使用兒童的變量數據而不是它自己的變量數據?
public class TestRPG1 {
static Player hero;
static Enemy dragon;
public static void main(String[] args) {
hero = new Player();
dragon = new Enemy();
while(dragon.hp > 0){
int choice = (int) (Math.random() * 2);
if(choice == 0)
hero.attack(dragon);
else
hero.magic(dragon);
}
System.exit(0);
}
}
public class Combatant {
int hp = 100;
int mp = 100;
int attack = 15;
int magic = 25;
int defence = 15;
int damage = 0;
String name = "null";
public void attack(Combatant target){
damage = (int) (Math.random() * attack);
System.out.println(name + " attacked the " + target.name + " for " + damage + " damage!");
target.hp -= damage;
System.out.println(target.name + " has " + target.hp + " HP left!");
}
public void magic(Combatant target){
damage = (int) (Math.random() * magic);
System.out.println(name + " shot a fireball at " + target.name + " for " + damage + " damage!");
target.hp -= damage;
System.out.println(target.name + " has " + target.hp + " HP left!");
}
}
public class Enemy extends Combatant{
String name = "Dragon";
}
public class Player extends Combatant{
String name = "Hero";
}
爲什麼你有Combatant中的'damage'屬性。你也可以在你的兩個方法中創建這個int。這看起來不合邏輯,因爲你只是使用這個變量來降低目標的HP值,這不是來自Combatant的真實屬性。 你可以簡單地在你的方法中做這個變量。 – 2009-11-22 08:05:13