Java setter 不会更改整数的值

标签 java private getter setter

编辑:添加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/

相关文章:

c++ - 初始化依赖于私有(private)模板类型的静态类成员 (C++)

javascript - ES6 : How to access a static getter from an instance

java - 当 MySQL 失去连接时,如何实现错误处理?

java - 我希望我的文件路径适用于使用 Java 的 linux 和 Windows 环境

java - 如果我需要在开始时评估条件,有没有办法避免 while(true) ?

java - 当我运行下面给出的代码时,我收到 java.sql.SQLSyntaxErrorException

C++:另一个类中的类作为类型?

c# - 单元测试私有(private)代码

java - java中如何访问另一个类的Arraylist

java - 转移所有权的方法的命名约定