[英]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. 我试图通过使用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());
}
}
I have another class that has a method that changes the integer x, by using the get and set method. 我还有另一个类,该类具有使用get和set方法更改整数x的方法。
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. 当我运行程序时,控制台将打印出0,但应该是1。 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.
然后,如果我在将变量设置为1后立即尝试使用Command中的getX方法打印x的值,它将打印出1。我试图查看是否可以在不使用静态变量的情况下执行此操作。
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. 您正在创建两个完全独立的/唯一的游戏对象,在其中一个中更改x并期望在另一个中更改x,而您发现这是行不通的。
Instead pass your Game object into your Command object via a setter method or constructor, and then change it. 而是通过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);
}
new Game();
creates an instance of Game
object. 创建一个
Game
对象的实例。 You have one instance in Command
and another instance in your main
method. 您在
Command
有一个实例,在main
方法中有另一个实例。
Using game.setX(int)
in instance of Command
will only affect the game
variable defined in that instance of Command
. 在
Command
实例中使用game.setX(int)
仅会影响在Command
实例中定义的game
变量。
See Java Static vs Instance 请参阅Java静态与实例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.