为什么这段代码会抛出NullPointerException?

时间:2013-12-29 14:14:54

标签: java nullpointerexception

我有以下代码而且我不知道为什么会抛出NullPointerException:

//File DungeonObject.java

public class DungeonObject
{
// === OBJECT LIST === //   
public static final DungeonObject dirt = (new DungeonObjectDirt(0)).setName("#").setTexture("dirt");

// === GLOBAL DUNGEON OBJECT === //
public static int objectID;
public static DungeonObject[] objectList = new DungeonObject[16];

private String name;
private Texture texture;

public DungeonObject (int id)
{
    if (objectList[id] != null)
    {
        throw new IllegalArgumentException("The slot " + id + " is already used by " + objectList[objectID].toString());
    } else {
        objectID = id;
        objectList[objectID] = this;
    }
}


public DungeonObject setName(String name)
{
    this.name = name;
    return this;
}

public DungeonObject setTexture (String key)
{       
    this.texture = GameManager.getTextureManager().getTexture(key);
    return this;
}

@Override
public String toString()
{
    return "Dungeon Object: " + this.name;
}
}

致电

System.out.println (DungeonObject.dirt);

1 个答案:

答案 0 :(得分:2)

失败的是你班级的初始化:

public class DungeonObject
{
public static final DungeonObject dirt = (new DungeonObjectDirt(0)).setName("#").setTexture("dirt");

...

public static DungeonObject[] objectList = new DungeonObject[16];

public DungeonObject (int id)
{
   if (objectList[id] != null)
    ....
}
}
  1. dirt字段的静态初始化程序运行;
  2. 它调用DungeonObject构造函数;
  3. 构造函数解引用objectList;
  4. 此时为null,因为其声明发生在dirt下方。