【问题标题】:Nested static class cannot return its static fields嵌套静态类无法返回其静态字段
【发布时间】:2012-04-14 16:12:29
【问题描述】:

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

由于某种原因,我在打印出 weapon.type 时出现了 default 字符串。为什么?我怎样才能让type成为Sword

【问题讨论】:

  • 你知道Character不拼写Cahracter对吧?
  • @Truth:至少它是一致的。就编译器而言,这更重要。
  • 谢谢,我知道 Character 的拼写方式。 =) 问题是为什么 weaponnull

标签: java oop


【解决方案1】:

你的问题出在这一行:

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

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

将其替换为:

this.weapon = new Weapon.Sword(); 

【讨论】:

    【解决方案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; 
    

    【讨论】:

    • 成功了。但由于某种原因,我在打印 weapon.type 时使用了 default 字符串。为什么?我怎样才能得到 type 字符串 Sword
    • 在回答中我也写给你如何解决这个问题:D
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-11
      • 2011-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多