为什么这会导致空指针异常?

时间:2011-09-07 16:13:49

标签: java initialization

我有这段代码:

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;
}

但是,一旦定义并初始化了sprite对象,我在另一个类中调用此函数时:

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

我得到一个空指针异常,指向包含它的行:

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

为什么会这样?

3 个答案:

答案 0 :(得分:5)

检查图像是否为空。这很可能是错误发生的地方。

答案 1 :(得分:1)

你正在某处创建一个Sprite并将构造函数传递给一个空图像。在你的构造函数中尝试做这样的事情

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

答案 2 :(得分:0)

如果imagenull,则会发生这种情况。在代码中的某个地方,您必须拨打此电话:

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

您可能希望在构造函数中添加一些引发null的{​​{1}}检查。这样可以轻松找到传递RuntimeException null

的代码
相关问题