我需要創建新的戰士,分配名稱,並獲得與GameCahracter類中指定的函數的描述。當我嘗試運行時 - 在weapon.type ; // <<Exception
上停止顯示weapon=null
。爲什麼?據我所知戰士的構造函數分配給變量weapon
一個鏈接到新武器。劍。然後使用可變武器,我應該可以訪問它的字段type
。這裏有什麼問題?嵌套的靜態類無法返回其靜態字段
abstract class GameCahracter{
public String name;
public String type;
public Weapon weapon;
public int hitPoints;
public String getDescription(){
return name + "; " +
type + "; " +
hitPoints + " hp; " +
weapon.type ; // << Exception
}
public static class Warrior extends Player{
public Warrior() {
type = "Warrior";
hitPoints = 100;
Weapon.Sword weapon = new Weapon.Sword();
}
}
abstract class Player extends GameCahracter {
}
abstract class Weapon {
public int damage;
public String type = "default";
public int getDamage(){
return this.damage;
}
public static class Sword extends Weapon{
public Sword() {
String type = "Sword";
int damage = 10;
}
}
}
GameCahracter.Warrior wr = new GameCahracter.Warrior();
wr.setName("Joe");
System.out.println(wr.getDescription());
EDIT1
出於某種原因,我在打印時出現default
字符串weapon.type
。爲什麼?我怎樣才能得到type
爲Sword
?
你知道'Character'不拼寫'Cahracter'對嗎? – 2012-04-14 16:16:04
@真理:至少它是一致的。就編譯器而言,這更重要。 – Makoto 2012-04-14 16:17:59
謝謝,我知道人物是如何拼寫的。 =)問題是爲什麼* weapon *是* null *。 – 2012-04-14 16:22:14