gpt4 book ai didi

Java - 指的是实现的类

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:18:55 26 4
gpt4 key购买 nike

我有一个小问题:我为我的游戏开发了一个“ExampleQuest”类,它扩展了抽象类 Quest。我这样做是为了创建单独的任务类。现在我的 ExampleQuest 类应该计算我的实体的死亡,所以我实现了我的 EntityListener。现在我必须在我的 Playstate 类中注册它以使一切正常,但这是我的实际问题:方法 Playstate.addEntityListener(this) 给了我一个空指针异常。我发现这个错误是由任何扩展类引起的。如果 ExampleQuest 不会扩展 Quest,则一切正常。我的 Quest 类没有任何错误,因为如果我用其他东西扩展 ExampleQuest,我也会得到一个空指针异常。

---> 所以我的解释是 Playstate.addEntityListener(this) 中的 this 在这种情况下指的是扩展类 Quest 而不是 EntityListener。我该如何解决我的问题?

public class ExampleQuest extends Quest implements EntityListener {

public ExampleQuest() {
super();
Playstate.addEntityListener(this); //gives me nullointer exception
}

//implemented method
public void entityDeathEvent(EntityEvent e) {

}
}

这是我的 Playstate 类(class)的一部分:

public class Playstate {

public static Set<EntityListener> entityListener;

public Playstate() {
entityListener = new HashSet<EntityListener>();
}

public static void addEntityListener(EntityListener listener) {
entityListener.add(listener);
}
}

编辑:这正常工作:

public class EventHandler implements EntityListener {

public EventHandler() {
Playstate.addEntityListener(this);
}
}

之所以有效,是因为 EventHandler 只是实现了一个类

最佳答案

你得到 NPE 的原因是 entityListener尚未初始化。 entityListener的原因尚未初始化是您的代码需要 Playstate 的实例在开始使用 addEntityListener 之前创建方法,但你调用 addEntityListener 创建 Playstate 的实例之前.

这是错误的:静态 变量不应在实例 构造函数中初始化。你需要在声明中这样做,就像这样

public static Set<EntityListener> entityListener = new HashSet<EntityListener>();

或在static初始化 block ,像这样:

public static Set<EntityListener> entityListener;

static {
entityListener = new HashSet<EntityListener>();
}

制作entityListener实例变量也可以,但是您需要提供一种方法来获取 Playstate来自 ExampleQuest 上下文的实例的构造函数。

关于Java - 指的是实现的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31301707/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com