java - 类变量不会改变
问题描述
我的代码如下所示:
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。
解决方案
当你使用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()
每次调用都会返回一个不同的值。
推荐阅读
- git - 为什么 git log --find-object 会为给定的 blob 获取两个具有不同内容的文件提交?
- css - css .fieldWrapper 类在哪里定义?(在 Django 文档中引用)
- docker - 如何将变量从 .gitlab.ci.yml 传递到 Dockerfile
- javascript - JavaScript 提示输入
- javascript - Babel 将字符串转译为 es2015
- docker - docker 版本 18.09 版本 --gpus all
- sql - SQL - 其中 MIN 日期正好是 7 天前
- java - 在适用于 Linux 和 Mac 的 Windows 上使用 Java 15 创建个性化 JRE
- excel - Excel VBA - 自动填充表单
- typescript - 为什么 TS 会自动检测我的类声明而不是我的类型别名?