我有以下代码而且我不知道为什么会抛出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);
答案 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)
....
}
}
dirt
字段的静态初始化程序运行; DungeonObject
构造函数; objectList
; null
,因为其声明发生在dirt
下方。