【发布时间】:2016-03-31 20:46:34
【问题描述】:
我有这门课:
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 中做到这一点? (我也尝试了第二个版本,我认为更有意义)
【问题讨论】:
-
请在下一篇文章中遵守正确的代码语法,这对需要阅读您问题的人有很大的不同。也就是说,这看起来很复杂。
if(thing)已经是语言的一部分,你为什么要编写一个静态真值评估器,它只是增加了间接性并使代码难以阅读?即使您需要检查集合,为什么不在Inventory类上将其作为实例方法? -
Java 是按值传递的。总是。这意味着方法参数始终是传递变量的本地副本。这意味着即使您为该本地/复制变量分配新值,原始变量也将保持不变。