Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 262
H3XXX Avatar asked Jul 09 '26 10:07

H3XXX


1 Answers

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).

like image 125
fge Avatar answered Jul 11 '26 22:07

fge



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!