H3XXX
H3XXX

Reputation: 647

java.lang.NullPointerException when running program

I have 4 classes. One is the abstract entity class, one is a ball class, one is the main class and the other is the screen class.

The ball class extends the entity class and has 5 variables.

The screen function has a paint method:

public void paint(Graphics g){
    super.paint(g);
    ball.paint(g);
}

And of course, to use ball.paint need to make an object for it. So, I make ball object:

Ball ball;

And then add this in the screen constructor, since I need to (Ball has a constructor which takes 5 variables):

public Screen(){
    ball = new Ball(ball.getWeight(), ball.getWidth(), ball.getHeight(), ball.getX(), ball.getX());
}

This comes up with no errors, but when I run the program, I get this error in the console:

Exception in thread "main" java.lang.NullPointerException
at h3x.engine.gfx.Screen.<init>(Screen.java:18)
at h3x.engine.Main.main(Main.java:16)

Line 16 of the main class is this:

frame.add(new Screen());

...and line 18 of the screen class is this:

ball = new Ball(ball.getWeight(), ball.getWidth(), ball.getHeight(), ball.getX(), ball.getX());

So my question is, why is this happening, and how can I fix it. I can put in the whole code in the classes if it is needed.

Thanks!

Upvotes: 2

Views: 1003

Answers (3)

David DeMar
David DeMar

Reputation: 2660

Your problem is this line:

ball = new Ball(ball.getWeight(), ball.getWidth(), ball.getHeight(), ball.getX(), ball.getX());

You're trying to assign values to ball that don't exist yet. Pass in some real values instead:

ball = new Ball(5, 4, 2, 7, 7);

Upvotes: 2

austin
austin

Reputation: 5866

Your line

Ball ball;

Isn't actually making a new Ball object, so the reference ball is set to null. When you try to retrieve the ball members in the constructor, it's throwing the NullPointerException. Using the members of an object instance in its own constructor is kind of suspect in this context.

Upvotes: 3

fge
fge

Reputation: 121712

You call:

ball = new Ball(ball.getXxx()....)

which means you expect to retrieve values from the instance you initialize. And before initialization is complete, it is null. Hence the NPE (short for NullPointerException).

Upvotes: 4

Related Questions