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!
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With