简体   繁体   English

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

[英]How can a static method change a variable? (Java)

I have this class:我有这门课:

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);
    }
}

The Inventory test class库存测试类

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();
    }
}

and this class with a method to try to change the inventory和这个类有一个方法来尝试改变库存

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


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

I would like to avoid using TestInv.smallknife = SKTrue.truth(TestInv.smallknife) and still change the variable but with a method.我想避免使用 TestInv.smallknife = SKTrue.truth(TestInv.smallknife) 并且仍然使用方法更改变量。 Is there a way that this can be done?有没有办法做到这一点? I want that the truth method does the variable changing and I don't want to do the pass by reference part in the Inventory Test class.我希望 truth 方法改变变量,我不想在 Inventory Test 类中执行引用传递部分。 Thanks.谢谢。 Is there a way to do this in Java?有没有办法在 Java 中做到这一点? (I also tried the second version which I think makes more sense) (我也尝试了我认为更有意义的第二个版本)

Assuming you don't want to reference the variables directly (ie TestInv.smallknife = blah ), the best practice in Java is to declare the variables as private and access them by getters/setters, eg:假设您不想直接引用变量(即TestInv.smallknife = blah ),Java 中的最佳实践是将变量声明为私有变量并通过 getter/setter 访问它们,例如:

class Inventory {

    private boolean smallknife;

    public boolean isSmallknife() {
        return smallknife;
    }

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

}

Now, you can do this:现在,您可以这样做:

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

It is called Encapsulation, you can read more about it here .它称为封装,您可以在此处阅读有关它的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM