2012-04-14 107 views
0

我需要创建新的战士,分配名称,并获得与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。为什么?我怎样才能得到typeSword

+2

你知道'Character'不拼写'Cahracter'对吗? – 2012-04-14 16:16:04

+0

@真理:至少它是一致的。就编译器而言,这更重要。 – Makoto 2012-04-14 16:17:59

+0

谢谢,我知道人物是如何拼写的。 =)问题是为什么* weapon *是* null *。 – 2012-04-14 16:22:14

回答

2

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

因此,与

weapon = new Weapon.Sword(); 

或更好的改线

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

Warrior构造与

this.weapon = new Weapon.Sword(); 

和你做了类似的错误在Sword构造,当你写

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

改变他们

this.type = "Sword"; 
this.damage = 10; 
+0

它工作。但出于某种原因,我在打印时使用* default *字符串* weapon.type *。为什么?我怎样才能得到*类型*字符串*剑*? – 2012-04-14 16:28:33

+1

在答案中,我写你如何解决这个问题:D – dash1e 2012-04-14 16:34:31

3

您的问题是在这条线:

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

您与当地的一个阴影的成员变量。

将其替换为:

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

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