简体   繁体   中英

Why does this cause a null pointer exception?

I have this code:

public class Sprite {
    protected float x;
    protected float y;
    protected Image image;
    protected Rectangle boundingBox;

    Sprite(float x, float y, Image image) {
        this.x = x;
        this.y = y;
        this.image = image;
        boundingBox = new Rectangle(x, y, 
            this.image.getWidth(), this.image.getHeight());
    }

...

public Rectangle getBoundingBox() {
    return boundingBox;
}

However when I call this function in a different class once the sprite object has been defined and initialized:

public static boolean collides(Sprite object1, Sprite object2) {
    return object1.getBoundingBox().intersects(object2.getBoundingBox());
}

I get a null pointer exception, pointing to the line that contains this:

this.image.getWidth(), this.image.getHeight());

Why is this?

Check to see if image is null. That's most likely where the error is coming from.

somewhere you are creating a Sprite and passing the constructor a null image. In your constructor try doing something like this

if (image == null) throw new Exception("Cannot create Sprite with null image")

It would happen if image is null . Somewhere in your code you must be making this call:

new Sprite(aFloat, anotherFloat, aNullValue); // aNullValue == null

You probably want to add some null checking in your constructor that throws a RuntimeException . This will make it easy to find the code that is passing in a null Image .

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