【发布时间】:2012-04-14 16:12:29
【问题描述】:
我需要创建新的战士,指定名称,并使用 GameCahracter 类中指定的函数获取他的描述。当我尝试运行时 - 它停在weapon.type ; // <<Exception 上,显示weapon=null。为什么?据我所知,分配给变量 weapon 的战士构造函数是指向新 Weapon.Sword 的链接。然后使用可变武器我应该能够访问它的字段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());
编辑1
由于某种原因,我在打印出 weapon.type 时出现了 default 字符串。为什么?我怎样才能让type成为Sword?
【问题讨论】:
-
你知道
Character不拼写Cahracter对吧? -
@Truth:至少它是一致的。就编译器而言,这更重要。
-
谢谢,我知道 Character 的拼写方式。 =) 问题是为什么 weapon 是 null。