Problem accessing variables before they are defined
I have this:
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;
}
However I get a null pointer exceptio开发者_StackOverflown when I run it. The class sprite is never used by itself, only used as a superclass.
The only way for image to be defined is through the constructor:
Sprite(float x, float y, Image image) {
this.x = x;
this.y = y;
this.image = image;
}
Probably because the variable image
is never initialized. Therefore image.getWidth()
and image.getHeight()
will fail with NullPointerException
s. Either initialize the variable. Or pass in image
or check for null
before you attempt to use it.
You're getting a NullPointerException
because image
hasn't been initialized.
EDIT:
The class sprite is never used by itself, only used as a superclass. The only way for image to be defined is through the constructor:
I'm not sure I understand your aversion to using a constructor. If Sprite
is being used as a superclass, then it's used just as much as if it was used by itself - so it needs to be fully baked.
protected Image image;
needs to be initialized if you want to get its width and height.
精彩评论