我试图通过使用getter和setter更改下面的变量x的值。

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


我还有另一个类,该类具有使用get和set方法更改整数x的方法。

package game;

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

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


当我运行程序时,控制台将打印出0,但应该是1。然后,如果我尝试在将变量设置为1后立即使用Command中的getX方法打印出x的值,它将打印出1。我试图查看是否有一种方法可以在不使用静态变量的情况下进行操作。

最佳答案

您正在创建两个完全独立的/唯一的游戏对象,在其中一个中更改x并期望在另一个中更改它,并且您发现这是行不通的。

而是通过setter方法或构造函数将Game对象传递到Command对象,然后对其进行更改。

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

10-01 02:15
查看更多