简体   繁体   中英

NullPointerException 7

I have 3 classes in the same package that are relevant to the problem: MainClass, Player and Ground. In Player.java, I need to access a variable that is declared in MainClass like so:

private static Ground ground;
...
ground= new Ground(440);

There's also a getter for ground that I want to use. This is Ground.java:

package cratejumper;

public class Ground {
    private int Y;

    public Ground(int height) {
        Y = height;
    }

    public int getY() {
        return Y;
    }

    public void setY(int y) {
        Y = y;
    }

}

Now I access ground from MainClass.java in Player.java like so:

private static Ground ground = MainClass.getGround();

But when I try to access ground.getY() in Player.java, it throws a nullpointerexception at runtime. I get no error when writing the code in eclipse. This is the part where I want to use ground in Player.java

39 if (Y + speedY >= ground.getY()-HEIGHT) {
40          Y = ground.getY()-HEIGHT;
41          speedY = 0; 
42          jumped=false;}

I can't find the error! I basically do the same thing with another class called Background.java without any problems.

private static Ground ground;

The above line is executed when the MainClass class is loaded (presumably, at the very beginning of the application). After this line has been executed, ground is null.

private static Ground ground = MainClass.getGround();

The above line is executed when the Player class is loaded (presumably, at the very beginning of the application).

And finally

ground= new Ground(440);

is executed, but we can't know when, because we don't have your full code. But presumably, it's executed after the Player class has been loaded.

Non-constant static fields are usually a sign of poor design. Consider passing objects around, instead of using static fields.

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