首页 > 解决方案 > 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确实变成了我想要的。

代码运行和编译没有错误/异常

标签: javaprivategettersetter

解决方案


问题是你有两个MovementDataStorage,一个在Main你打印的类中,另一个在ActionsMovement你设置它的值。

一种解决方案是使用MovementDataStoragefrom 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;
    }
}

推荐阅读