如何在不使用静态的情况下从另一个类更改变量?

时间:2014-05-10 19:11:00

标签: java

我试图通过使用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后尝试使用命令中的getX方法打印出x的值,则会打印出1.我试图查看是否有一种方法可以在不使用静态变量的情况下执行此操作

2 个答案:

答案 0 :(得分:5)

你正在创建两个完全独立/独特的游戏对象,将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);
   }

答案 1 :(得分:0)

new Game();创建Game对象的实例。您在Command中有一个实例,在main方法中有另一个实例。

game.setX(int)的实例中使用Command只会影响该game实例中定义的Command变量。

请参阅Java Static vs Instance