0

我需要创建新的战士,指定名称,并使用 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

4

3 回答 3

3

您的问题出在这一行:

Weapon.Sword weapon = new Weapon.Sword(); 

你用一个本地变量来隐藏你的成员变量。

将其替换为:

this.weapon = new Weapon.Sword(); 
于 2012-04-14T16:23:16.163 回答
2

在这一刻,您的构造函数将weapon字段留给null. 只需创建一个Sword一旦超出范围就被垃圾的实例。

所以换行

Weapon.Sword weapon = new Weapon.Sword(); 

在你的Warrior构造函数中

weapon = new Weapon.Sword(); 

或者更好

this.weapon = new Weapon.Sword(); 

Sword并且在编写时在构造函数中犯了类似的错误

String type = "Sword";
int damage = 10; 

改变他们

this.type = "Sword";
this.damage = 10; 
于 2012-04-14T16:22:06.153 回答
1

您会在该行遇到异常,因为weapon您的实例中的变量GameCahracter为空。任何地方都没有设置它的代码。构造函数中的代码Warrior设置一个新的局部变量的值,而不是类中的成员变量。

于 2012-04-14T16:24:08.680 回答