我需要创建新的战士,指定名称,并使用 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
出于某种原因,我default
在打印时有字符串weapon.type
。为什么?我怎样才能type
成为Sword
?