Can you show us more code? Methinks something else is going on here.
int
variables will default initialize to 0 in Java, and if I use your snippet, and instantiate a Ghost
, all its int
members are 0.
So from your comments, I think there might be an issue with your code, like you are accidentally setting direction
when using Ghost.setX
or Ghost.setY
.
In my extremely simple class implementation, this testing code works exactly as intended.
Edited since code was posted
Okay so I have a class based on your code. I don't see anything wrong with the other functions, since very few classes actually alter direction
. I removed those extra functions because they didn't modify direction except for one thing that would set it to 0.
You should try a very reduced test case to see if your code works. Try this:
import junit.framework.Assert;
class Ghost
{
private int x, y, direction;
public int getX() { return x; }
public void setX(int x) { this.x = x; }
public int getY() { return y; }
public void setY(int y) { this.y = y; }
public int getDirection() { return direction; }
public void setDirection(int direction) { this.direction = direction; }
public static void main (String [] args)
{
Ghost g = new Ghost();
g.setX(10);
g.setY(20);
Assert.assertEquals(g.getDirection(), 0);
System.out.println(g.getX() + " " + g.getY() + " " + g.getDirection());
}
}
Everything still works here, so try that code as is. This is purely your code, and if it works (and it should), then there's other code like a user of your class that is doing something.
Standalone, your code should work just fine.
Use the Debugger
Are you familiar with a debugger? If you are using Eclipse or NetBeans, then you should get friendly with using the debuggers integrated into their environments. This should really help you track down when direction
changes values by placing a watch on it.
Using a debugger is way beyond the scope of this answer; it's something you really have to read up on and try yourself.
Here's a link for debugging with Eclipse: