编辑:添加MovementDataStorage data = new MovementDataStorage();到主类,如注释中指出的那样进行澄清。
我有 3 个类,都在同一个包中。 Main 类中 main 方法的代码片段:
ActionsMovement move = new ActionsMovement();
MovementDataStorage data = new MovementDataStorage();
move.goForward();
System.out.println(data.getLocationNorth()); //this would show 0, intended result is 1
我的 ActionsMovement 类具有以下代码片段:
MovementDataStorage data = new MovementDataStorage();
public void goForward()
{
if (data.getDirection().equals("North")) {
data.setLocationNorth(data.getLocationNorth() + 1);
}
}
最后,我的 MovementDataStorage 具有以下代码片段:
private int locationNorth;
private String direction = "North";
public int getLocationNorth() {
return locationNorth;
}
public void setLocationNorth(int locationNorth) {
this.locationNorth = locationNorth;
}
public String getDirection() {
return direction;
}
public void setDirection(String direction) {
this.direction = direction;
}
当 move.goForward();
运行,值为 int locationNorth
不增加 - 我尝试从 main 方法和 goForward
内部检查该值方法。
如果我手动更改int locationNorth
值,我可以看到变化。如果我通过move.goForward();
来做到这一点看起来并没有改变。
如果在我的main
我添加的方法:
data.setLocationNorth(data.getLocationNorth()+1);
System.out.println(data.getLocationNorth());
int locationNorth
的值确实变成了我想要的样子。
代码运行和编译没有错误/异常
最佳答案
问题是您有两个 MovementDataStorage
,一个位于您打印的 Main
类中,另一个位于您设置其值的 ActionsMovement
中。
一种解决方案是使用 ActionsMovement
中的 MovementDataStorage
。
class Main {
ActionsMovement move = new ActionsMovement();
move.goForward();
System.out.println(move.getData().getLocationNorth());
}
class ActionsMovement {
public MovementDataStorage getData() {
return this.data;
}
}
如果您在 main 中需要 MovementDataStorage
,您可以创建一个实例并将其作为参数发送
class Main {
MovementDataStorage data = new MovementDataStorage();
ActionsMovement move = new ActionsMovement(data);
move.goForward();
System.out.println(move.getData().getLocationNorth());
}
class ActionsMovement {
MovementDataStorage data;
public ActionsMovement(MovementDataStorage data) {
this.data = data;
}
public ActionsMovement() {
this.data = new MovementDataStorage();
}
public MovementDataStorage getData() {
return this.data;
}
}
关于Java setter 不会更改整数的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60149379/