我需要创建新的战士,分配名称,并使用 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());
<小时/>
编辑1
出于某种原因,我有 default
打印时的字符串 weapon.type
。为什么?我怎样才能得到type
成为Sword
?
最佳答案
您的问题在这一行:
Weapon.Sword weapon = new Weapon.Sword();
您使用本地成员变量来隐藏您的成员变量。
将其替换为:
this.weapon = new Weapon.Sword();
关于java - 嵌套静态类无法返回其静态字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10155121/