java - Java setter 不改变整数的值
问题描述
编辑:添加 MovementDataStorage 数据 = 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
不会增加 - 我尝试从主方法和goForward
方法内部检查值。
如果我手动更改int locationNorth
值,我可以看到更改。如果我通过move.goForward();
它似乎不会改变。
如果在我的main
方法中添加:
data.setLocationNorth(data.getLocationNorth()+1);
System.out.println(data.getLocationNorth());
的价值int locationNorth
确实变成了我想要的。
代码运行和编译没有错误/异常
解决方案
问题是你有两个MovementDataStorage
,一个在Main
你打印的类中,另一个在ActionsMovement
你设置它的值。
一种解决方案是使用MovementDataStorage
from ActionsMovement
。
class Main {
ActionsMovement move = new ActionsMovement();
move.goForward();
System.out.println(move.getData().getLocationNorth());
}
class ActionsMovement {
public MovementDataStorage getData() {
return this.data;
}
}
如果您需要MovementDataStorage
在 main 中创建一个实例并将其作为参数发送
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 - 调用容器“xxxxxx”时出错:在 Redhat Business Central 上解组输入时出错
- quarkus - Quarkus 休眠验证异常未显示在控制台上
- android - 在设置菜单项的可见性时如何解决这个空指针异常?
- python - 在 Tkinter 中切换窗口时,Python-Listbox 项目不会终止
- android - 当我们有 ViewModels 时,我们还需要 onSaveInstanceState() 吗?
- c++ - 'char **':dynamic_cast 的目标类型无效
- gcc - GCC 上 x86 intel asm 中方括号前的偏移量
- mysql - 我的 SQL 数据库不一致(基数与自动增量)
- java - 如何在 sublime text 3 中为 java 构建系统,它也支持包?
- c# - EF Core - 如何在包含的集合中包含项目的集合