TACO
TACO

Reputation: 145

How can I change the variable from another class without using static?

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.

Upvotes: 0

Views: 2412

Answers (2)

Lindlof
Lindlof

Reputation: 2162

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

Upvotes: 0

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

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);
   }

Upvotes: 5

Related Questions