简体   繁体   English

从另一个类调用类函数。 错误

[英]Calling class function from another class. Error

Simplified: Two classes. 简化:两节课。 X and Y. X和Y。

Y extends X. Y延伸X。

In XI call: 在XI通话中:

    Y periodic;

Then in XI call one of Y's functions: 然后在XI中调用Y的功能之一:

periodic.conditionDepreciate();

The actual function block in Y is: Y中的实际功能块为:

    public void conditionDepreciate() {
    ActionListener conditionDepreciation = new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
              if (ameba.health > 0) {
                  ameba.health -= 1;
              }
        }
    };
        new Timer(conditionDelayCount * 1000, conditionDepreciation).start();
}

But regardless of what the function does I get an error coming from the X file saying: 但是,无论使用什么功能,我都会从X文件中收到一条错误消息:

Exception in thread "main" java.lang.NullPointerException 线程“主”中的异常java.lang.NullPointerException
at X.(X.java:71) 在X.(X.java:71)
at X.main(X.java:245) 在X.main(X.java:245)

Line 71 is referring to when I call: 当我打电话时,第71行指的是:

periodic.conditionDepreciate();

Could someone help explain the error? 有人可以帮助解释该错误吗?

EDIT: 编辑:

I want X to call various functions of Y. Which are all, basically, periodic event timers. 我希望X调用Y的各种函数。基本上,所有这些都是周期性事件计时器。

I originally had the timers in the X class file but to help with readability I moved into its own class file. 我最初在X类文件中具有计时器,但是为了提高可读性,我将其移至其自己的类文件中。

I'm not sure what something like this needs to be initialized with... Y extends X so it should get all its values from X? 我不确定需要使用类似的内容来初始化... Y扩展了X,因此它应该从X获取所有值吗? (I think...) (我认为...)

I posted one of the timer functions above - do I need to tell the Y class file what ameba.health is? 我在上面发布了一个计时器函数-我需要告诉Y类文件ameba.health是什么吗? or ? 要么 ? I guess I'll just have to look up functions and classes >.> 我想我只需要查找函数和类>。

似乎没有periodic引用的问题,因为您从未创建对象,例如

Y periodic = new Y();

Presumably the value of periodic is null. 大概periodic值为空。 That's the default for static/instance fields. 这是静态/实例字段的默认设置。 You need to assign a non-null reference to it before you can call a method via it. 您需要为其分配一个非null的引用,然后才能通过它调用方法。 We don't have enough information about what the value of periodic should be - whether you ought to be creating a new instance somewhere, or using an existing one - but calling a method on a null reference will give a NullPointerException ... 我们没有关于价值是什么足够的信息, periodic 应该是-你是否应该在某个地方创建一个新的实例,或者使用一个现有的-但呼吁空引用的方法会给出一个NullPointerException ...

If you tell us more about which instance you expected the method to be called on, we may be able to help further. 如果您告诉我们您希望在哪个实例上调用该方法的更多信息,我们可能会提供进一步的帮助。

Note that the fact that Y extends X is irrelevant here. 注意,此处Y扩展X的事实无关紧要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM