簡體   English   中英

Java - 在沒有方法的情況下編輯實例變量

[英]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。

如果需要將xMeteryMeter初始化為基於xy的值,則只需像其他字段一樣聲明它們即可:

public int xMeter;

並在構造函數中初始化它們的值:

public newBody(int x, int y){
    // initialize x and y ...
    this.xMeter = x * distanceScale;

正如其他人所提到的,當初始化xMeter時,構造函數尚未被調用且x仍為0 ,因此xMeter的值xMeter0

要更改它,必須在構造函數中初始化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 )的值,在這些方法中,還要更新xMeteryMeter的值。 這樣,無論何時想要更改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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM