[英]Java - Edit instance variables without a method
我对Java还是很陌生,并且我一直在寻找改善代码的方法。 但是,即使有可能,我似乎也没有得到。
假设我有这个代码(我编辑了不相关的部分,所以代码可能看起来很奇怪):
public class NewBody {
public static int distanceScale = 5;
public int x, y;
public float xMeter = x * distanceScale;
public float yMeter = y * distanceScale;
public NewBody(int x, int y){
this.x = x;
this.y = y;
}
public void pixToMeter(){
this.xMeter = distanceScale * this.x;
}
如果我不调用pixToMeter()并尝试直接使用“instance.xMeter”,它只返回vululue 0,即使我已经在构造函数中设置了x变量。
所以我的问题是:有没有办法在不调用方法的情况下正确设置变量? 这似乎是非常不必要的,因为我甚至没有传递参数。
对不起,我的英语不好,希望您能理解我的意思。
当x仍然为零时,xMeter的初始化完成。
这是实际发生的事情:
public NewBody(int x, int y) {
// All fields are zeroed: 0, null, 0.0.
super(); // Object constructor, as Object is the parent class.
// Those fields that are initialized:
xMeter = this.x * distanceScale; // 0.0f * 5
yMeter = this.y * distanceScale;
// The rest of the constructor:
this.x = x;
this.y = y;
}
对于依赖值:
public final void setX(int x) {
this.x = x;
xMeter = this.x * distanceScale;
}
并应用DRY原理(不要重复自己):可以删除xMeter的初始化,然后在构造函数中调用setX(x)。
在构造函数中调用时,使setX
final很重要,即:不可重写。
问题的根源在这里:
public float xMeter = x * distanceScale;
问题是您要在构造函数外部初始化此实例变量。 结果,由于x
被初始化为0,因此乘法的结果也是0。
如果需要将xMeter
和yMeter
初始化为基于x
或y
的值,则只需像其他字段一样声明它们即可:
public int xMeter;
并在构造函数中初始化它们的值:
public newBody(int x, int y){
// initialize x and y ...
this.xMeter = x * distanceScale;
正如其他人所提到的,当初始化xMeter
时,构造函数尚未被调用且x
仍为0
,因此xMeter
的值xMeter
为0
。
要更改它,必须在构造函数中初始化x
更新xMeter
的值,如下所示:
public NewBody(int x, int y){
this.x = x;
this.y = y;
// update x and y meter
xMeter = x * distanceScale;
yMeter = y * distanceScale;
}
但是,您提到了如何让xMeter
在每次x
更改时也进行更新。 因为它与您当前的代码一致,所以不会发生这种情况。 但是,我的建议是创建一个方法来改变x
(和y
)的值,在这些方法中,还要更新xMeter
和yMeter
的值。 这样,无论何时想要更改x
,都要调用方法,它也会更新其他值。
尝试添加以下方法,并将构造方法更改为此:
// called setter methods
public void setX(int x) {
this.x = x;
this.xMeter = x * distanceScale;
}
public void setY(int y) {
this.y = y;
this.yMeter = y * distanceScale;
}
// constructor
public NewBody(int x, int y){
setX(x);
setY(y);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.