Stephan
Stephan

Reputation: 17981

Debugging multiple variables with same name in Eclipse

I got a null pointer exception when referencing position. In the debug view i found 2 different variables with the same name. One seems to be null and has a green circle, one is the correct variable and has a blue triangle next to it.

The View of my Debugger

Why is my code referencing the null variable and why would there be 2 copies of that variable in memory?

The position gets set in the constructor here

public Obstacle(int x, int y) {
  position = new PVector(x,y);

}

The constructor gets called from a level generator class here

obstacle1 = new Obstacle(levelWidth/4, 375);
obstacle2 = new Obstacle(levelWidth/2, 375);
obstacle3 = new Obstacle(levelWidth*3/4, 375);

Not sure what other code to show.

Upvotes: 0

Views: 915

Answers (2)

s106mo
s106mo

Reputation: 1253

The problem is that you have the field point both in the superclass and the subclass. Most likely you are setting the field of the superclass correctly but "forget" to set the field of the subclass. Consider following example:

class Super {
    Boolean exist;
}

class Sub extends Super {
    Boolean exist;
    Sub() {
        super.exist = true;
    }
}

when you execute following code::

Sub sub = new Sub();
System.out.println(sub.exist);

null will be printed because its exist field of Sub has not been initiated.

To prevent such errors in the future, do not use duplicated fields in subclasses and use getter methods to access the field values.

Upvotes: 1

Thiago Falcao
Thiago Falcao

Reputation: 5013

Green circle indicates a public method

Red square indicates a private method

Yellow diamond indicates a protected method

Blue triangle indicates default (package visible) method

You can see the difference between these two icons in What do the icons for methods in Eclipse mean?

Upvotes: 1

Related Questions