(Java) 修改 public 个静态变量

(Java) modifying public static variables

这里有点新。

无论如何,我对Java比较陌生,这些是uni的一些练习题,我有一个问题。 我该如何做到 TOTAL_RESERVES 不能被外部修改。现在如果我说

Gold.TOTAL_RESERVES = 500;

这改变了它的价值。 我如何做到只有构造函数更改值。

我知道我可以将其设为私有,但我希望它位于 API。

这是参考文献API

http://www.eecs.yorku.ca/course_archive/2014-15/W/1030/sectionZ/hw/doc/Gold/index.html

public class Gold
{
    static int TOTAL_RESERVES = 100;
    private int weight;

    public Gold (int weight)
    {
        TOTAL_RESERVES -= weight;
        this.weight = weight;
    }

    public int getWeight()
    {
        return this.weight;
    }

    public static int remaining()
    {
        return TOTAL_RESERVES;
    }

    @Override
    public String toString ()
    {
        return "Weight = " + this.weight;
    }
}

谢谢!

老实说,将其设为私有是解决此问题的最佳方法。这不是您想要的答案……但它是最好的解决方案。

在文档中,TOTAL_RESERVES 的字段详细信息是 public static final int TOTAL_RESERVESfinal 修饰符意味着 TOTAL_RESERVES 是一个常量。要跟踪当前储备,您需要创建另一个变量,如下所示:

private static int CURRENT_RESERVES = TOTAL_RESERVES;

并用它来减去重量和return剩余的储备。

关于您指定的 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) {

    }
}