(Java)修改公共静态变量

时间:2015-02-07 03:37:05

标签: java constructor static private public

有点新的。

无论如何,我对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;
    }
}

谢谢!

3 个答案:

答案 0 :(得分:0)

老实说,我认为私有化是解决这个问题的最佳方法。它不是你想要的答案......但它是最好的解决方案。

答案 1 :(得分:0)

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

private static int CURRENT_RESERVES = TOTAL_RESERVES;

用它来减去重量并返回剩余的储备。

答案 2 :(得分:0)

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

    }
}
相关问题