静态方法如何改变变量? (JAVA)

时间:2016-03-31 20:46:35

标签: java class variables

我有这堂课:

class Inventory {
    boolean smallknife = false;
    boolean SRLockerkey = false;
    void checkinv () {
        System.out.println("You have the following items in your inventory: ");
        System.out.println(smallknife);
        System.out.println(SRLockerkey);
    }
}

库存测试类

class InvTester {
    public static void main(String args[]) {
        Inventory TestInv = new Inventory();
        System.out.println("This program tests the Inventory");
        SKTrue.truth(TestInv.smallknife);
        TestInv.checkinv();
    }
}

这个类有一个尝试更改库存的方法

class SKTrue {
    static boolean truth(boolean smallknife) {
        return true;
    }
}


class SKTrue {
   static void truth(boolean smallknife) {
    smallknife = true;
  }
}

我想避免使用TestInv.smallknife = SKTrue.truth(TestInv.smallknife)并仍然使用方法更改变量。有没有办法可以做到这一点?我希望真值方法改变变量,我不想在Inventory Test类中通过引用部分进行传递。谢谢。有没有办法在Java中这样做? (我也试过第二个版本,我认为更有意义)

1 个答案:

答案 0 :(得分:4)

假设您不想直接引用变量(即TestInv.smallknife = blah),Java中的最佳实践是将变量声明为私有并通过getter / setter访问它们,例如:

class Inventory {

    private boolean smallknife;

    public boolean isSmallknife() {
        return smallknife;
    }

    public void setSmallknife(boolean smallknife) {
        this.smallknife = smallknife;
    }

}

现在,你可以这样做:

Inventory TestInv = new Inventory();
TestInv.setSmallknife(SKTrue.truth(blah));

它被称为封装,你可以阅读更多关于它here