我对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“,那么它只返回值0,即使我已经在构造函数中设置了x变量。
所以我的问题是:有没有一种方法可以在不调用方法的情况下正确地设置变量?这似乎是非常不必要的,因为我甚至没有向它传递参数。
对不起,我的英语很差,我希望你能理解我想说的话。
发布于 2015-01-07 08:04:31
当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非常重要,即:不可重写。
发布于 2015-01-07 08:11:10
问题的根源在这里:
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;发布于 2015-01-07 08:27:15
正如其他人所提到的,当xMeter被初始化时,构造函数还没有被调用,x仍然是0,所以xMeter的值也是0。
要改变这一点,必须在构造函数中初始化xMeter之后更新x的值,如下所示:
public NewBody(int x, int y){
this.x = x;
this.y = y;
// update x and y meter
xMeter = x * distanceScale;
yMeter = y * distanceScale;
}但是,您也提到了每次更改x时,您希望xMeter如何更新。因为它与您当前的代码站在一起,这不会发生。但是,我的一个建议是创建一个方法来更改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);
}https://stackoverflow.com/questions/27809346
复制相似问题