首页 > 解决方案 > 类变量不会改变

问题描述

我的代码如下所示:

public class Boxes {

    float length = 0;
    float width = 0;
    float height = 0;

    float fmax = (this.getVol() / 40000);
    int max = (int) fmax;

    String[] items = new String[max];

    public float getVol() {

        return length*width*height;

    }

}

当我有这个类的一个实例并且我将变量“长度”、“宽度”和“高度”设置为非零值时,变量“fmax”不会改变。相反,我注意到它使用默认情况下在类中分配的值,它们都是 0。

标签: java

解决方案


当你使用Boxes你做这个:

Boxes boxes = new Boxes();

此时状态boxes

长度 = 0; 宽度 = 0; 高度 = 0; fmax = (0 / 40000);

由于长度、宽度和高度都用 0 初始化,所以getVol() = 0. 所以fmax=0一开始。

现在让我们假设您更改了这些值:

boxes.length = 1;
boxes.height = 1;
boxes.width = 1;

这个动作不会改变boxes.fmax,因为它被初始化为 0 并且不会getVol再次调用。如果你想改变它,你可以使用一个函数getFmax()来代替。

float getFmax() {
    return this.getVol() / 40000;
}

这个函数getVol()每次调用都会返回一个不同的值。


推荐阅读