修改类中的变量

时间:2018-04-20 06:08:16

标签: java

所以说我有一个类,它有一些我希望能够在类中的几个方法中递增的变量。我该如何编辑它们?

我一直试图这样做,但它不起作用。我做一些阅读的理解是java传递了一个对象的副本,所以当我在方法中编辑它时,它实际上并没有编辑原始值。它只是对副本进行调整,然后一旦完成,值就会消失。

我确实读过一些关于必须从方法中返回值以更新原始内容的内容,但后来我对如何调用它感到有些困惑。

1 个答案:

答案 0 :(得分:1)

简单示例:

public class Thing {
    private int someInt = 0; // optional, can be left unset as well if you remember to assign it in the constructor or some method.

    public static void main(String[] args) {
        Thing yourobj = new Thing();
        System.out.println("Then: "+yourobj.getThatInt());
        yourobj.increment();
        System.out.println("Now: "+yourobj.getThatInt());
    }

    public int getThatInt() {
        return this.someInt;
    }

    public void increment() {
        this.someInt += 1;
    }
}