我需要创建新的战士,分配名称,并获得与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