0

How come dont get a NullPointerException when I call w.getX() in constructor Turtle(...) but when i call it in method getX() i do.

I'm guessing it has something to do with the public and private statements?

public class Turtle {
    int x, y;
    private boolean pen;
    private double rikt;
    private SimpleWindow w;

    public Turtle(SimpleWindow w, int x, int y) {
        w.moveTo(x, y);
        System.out.println(w.getX());
        rikt = Math.PI / 2;
        pen = false;
    }

    public int getX() {
        return w.getX();
    }

    public int getY() {
        return w.getY();
    }

}

The main looks like this:

public class TurtleDrawSquare {
     public static void main(String[] args) {
        SimpleWindow w = new SimpleWindow(600, 600, "TurtleDrawSquare");
        Turtle t = new Turtle(w, 300, 300);
        t.penDown();
        for (int i = 0; i < 4; i++) {
            t.forward(100);
            t.left(90);
        }
    }
}
Datz
  • 3,156
  • 3
  • 22
  • 50
w474490
  • 29
  • 4
  • Maybe a duplicate. But I guess in this case the questioner did expect `w`to be assigned automatically in the constructor, so the references question probably would not help him. – Datz May 17 '19 at 20:45

1 Answers1

4

Your description is not really clear. But inside your Turtle constructor, you get w as parameter. So when the parameter is not null, then there is no NPE.

But the instance variable w is never set. So when you call getX, you get a NPE because w is never set.

So maybe you simply add a

this.w = w;

inside your Turtle constructor to set the instance variable. Then w is set and w.getX() will not throw an NPE.

Konrad Neitzel
  • 736
  • 3
  • 7
  • 1
    Please don't get into the habit of answering these questions that have been asked thousands of times before. Instead flag to close with a canonical duplicate. (Eventually, you'll also be able to vote.) – Sotirios Delimanolis May 17 '19 at 21:44
  • I am sorry. I still have to learn more about this Stack Overflow thing. Sorry for off topic now, but I have a strong MSDN Forum background a few years ago. And in there it was really important to get all questions fully answered and then also marked as answered. (I was quite active there, was even a moderator and before I left I was even active inside a so called "Forum Ninja" Team around Ed Price...What I want to say: I think I understood your point, I will try to change my activity but please be patient with me. And thank you for your Advice. – Konrad Neitzel May 17 '19 at 22:13