Der*_*rek 1 java initialization
我有这个:
public class Sprite
{
protected float x;
protected float y;
protected Image image;
protected Rectangle boundingBox;
public Rectangle getBoundingBox()
{
boundingBox = new Rectangle(x, y,
image.getWidth(), image.getHeight());
return boundingBox;
}
Run Code Online (Sandbox Code Playgroud)
但是,当我运行它时,我得到一个空指针异常.类精灵从不单独使用,仅用作超类.
定义图像的唯一方法是通过构造函数:
Sprite(float x, float y, Image image) {
this.x = x;
this.y = y;
this.image = image;
}
Run Code Online (Sandbox Code Playgroud)
可能是因为变量image从未初始化.因此image.getWidth(),image.getHeight()将失败与NullPointerExceptions.初始化变量.或在您尝试使用之前传入image或检查null.