0

I have tried to change the value of the variable x below by using a getter and setter.

package game;
public class Game {
private int x;
private int y;

public int getX() {
    return this.x;
}

public int getY() {
    return this.y;
}

public void setX(int x) {
    this.x = x;
}

public void setY(int y) {
    this.y = y;
}

public static void main(String[] args) {
    Game game = new Game();
    Command command = new Command();
    command.changeX();
    System.out.println(game.getX());
}
}

I have another class that has a method that changes the integer x, by using the get and set method.

package game;

public class Command {
Game game = new Game();

public void changeX() {
    int x = game.getX();
    game.setX(x + 1);
}
}

When I run the program the console prints out 0, but it is supposed to be one. Then, if I try to print out the value of x using the getX method in Command right after I set the variable to one, it prints out 1. I am trying to see if there is a way I can do this without using static variables.

TACO
  • 145
  • 1
  • 1
  • 6
  • 3
    The instance of `Game` that your `Command` refers to is entirely different to the instance of `Game` that your `main` method refers to. – Jon Skeet May 10 '14 at 19:12

2 Answers2

5

You're creating two completely separate/unique Game objects, changing x in one and expecting it to change in the other, and as you're finding out, this won't work.

Instead pass your Game object into your Command object via a setter method or constructor, and then change it.

public static void main(String[] args) {
    Game game = new Game();
    Command command = new Command(game); // *** note constructor change
    command.changeX();
    System.out.println(game.getX());
}

public class Command {
   private Game game; //  note it's not initialized here

   // pass Game in via a constructor parameter
   public Command(Game game) {
      this.game = game;   // and set the field with it
   }

   public void changeX() {
      // now you'll be changing the state of the same Game object
      int x = game.getX();
      game.setX(x + 1);
   }
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
0

new Game(); creates an instance of Game object. You have one instance in Command and another instance in your main method.

Using game.setX(int) in instance of Command will only affect the game variable defined in that instance of Command.

See Java Static vs Instance

Community
  • 1
  • 1
Lindlof
  • 2,152
  • 2
  • 17
  • 26