(Java)修改公共静态变量
这里有点新 不管怎么说,我对Java还比较陌生,这些是uni的一些实践问题,我有一个问题。 我怎样才能使总储量不被外界改变。现在如果我说 黄金总储量=500 这会改变它的价值。 如何使其仅由构造函数更改值 我知道我可以让它私有化,但我希望它在API中 这是参考API(Java)修改公共静态变量,java,constructor,static,private,public,Java,Constructor,Static,Private,Public,这里有点新 不管怎么说,我对Java还比较陌生,这些是uni的一些实践问题,我有一个问题。 我怎样才能使总储量不被外界改变。现在如果我说 黄金总储量=500 这会改变它的价值。 如何使其仅由构造函数更改值 我知道我可以让它私有化,但我希望它在API中 这是参考API 谢谢 老实说,保密是解决这个问题的最好办法。这不是你想要的答案…但这是最好的解决方案 在文件中,总储量的字段详细信息为公共静态最终总储量。最后一个修饰符表示总储量为常数。要跟踪当前储备,您需要创建另一个变量,如下所示: privat
谢谢 老实说,保密是解决这个问题的最好办法。这不是你想要的答案…但这是最好的解决方案 在文件中,总储量的字段详细信息为公共静态最终总储量。最后一个修饰符表示总储量为常数。要跟踪当前储备,您需要创建另一个变量,如下所示:
private static int CURRENT_RESERVES = TOTAL_RESERVES;
然后用它减去重量并返回剩余的储量。关于您指定的API,您的代码应该如下所示:
public class Gold {
public static final int TOTAL_RESERVES = 100;
private int weight;
private static int remainingWeight;
static {
remainingWeight = TOTAL_RESERVES;
}
public Gold(int weight) {
if (remainingWeight <= 0) {
this.weight = 0;
remainingWeight = 0;
}
else {
if (weight >= 0) {
if (weight > remaining())
this.weight = remaining();
else
this.weight = weight;
} else {
this.weight = 0;
}
remainingWeight -= this.weight;
}
}
public int getWeight() {
return this.weight;
}
public static int remaining() {
return remainingWeight;
}
@Override
public String toString() {
return "Weight = " + this.weight;
}
public static void main(String[] args) {
}
}
如果在整个宇宙中有一个字段是私有的,那么它就是Gold.TOTAL_RESERVES.Yes,这也是我的想法,但是API显示它也必须做Javadoc,所以它是公共的可以记录私有变量吗?这似乎是错误的。xD@Nesan为什么要使其静止?使用final并使其成为constant@Nesan在API中明确指定了声明:public static final int TOTAL_RESERVES,那么为什么要更改该声明呢?是的,我也这么认为,但API显示它也必须执行Javadoc,所以它是公共的=/但是剩余的不总是会返回100吗?嘿,谢谢你!顺便问一下,静态{remainingWeight=TOTAL_RESERVES;}到底做了什么?新语法对我来说。@Nesan是一个静态初始化块,你可以从这里学到更多:是的,这似乎是最合理的解决方案。我想用一个领域做这件事是不可能的。谢谢我明天和教授商量一下。
public class Gold {
public static final int TOTAL_RESERVES = 100;
private int weight;
private static int remainingWeight;
static {
remainingWeight = TOTAL_RESERVES;
}
public Gold(int weight) {
if (remainingWeight <= 0) {
this.weight = 0;
remainingWeight = 0;
}
else {
if (weight >= 0) {
if (weight > remaining())
this.weight = remaining();
else
this.weight = weight;
} else {
this.weight = 0;
}
remainingWeight -= this.weight;
}
}
public int getWeight() {
return this.weight;
}
public static int remaining() {
return remainingWeight;
}
@Override
public String toString() {
return "Weight = " + this.weight;
}
public static void main(String[] args) {
}
}