Derek
Derek

Reputation: 892

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

Upvotes: 1

Views: 97

Answers (3)

Chris Aldrich
Chris Aldrich

Reputation: 1932

Probably because the variable image is never initialized. Therefore image.getWidth() and image.getHeight() will fail with NullPointerExceptions. Either initialize the variable. Or pass in image or check for null before you attempt to use it.

Upvotes: 9

Paul Bellora
Paul Bellora

Reputation: 55223

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.

Upvotes: 4

talnicolas
talnicolas

Reputation: 14053

protected Image image;

needs to be initialized if you want to get its width and height.

Upvotes: 2

Related Questions