简体   繁体   中英

Calling class function from another class. Error

Simplified: Two classes. X and Y.

Y extends X.

In XI call:

    Y periodic;

Then in XI call one of Y's functions:

periodic.conditionDepreciate();

The actual function block in Y is:

    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:

Exception in thread "main" java.lang.NullPointerException
at X.(X.java:71)
at X.main(X.java:245)

Line 71 is referring to when I call:

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.

I originally had the timers in the X class file but to help with readability I moved into its own class file.

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? (I think...)

I posted one of the timer functions above - do I need to tell the Y class file what ameba.health is? 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. 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. 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 ...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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