如果我有一個如下的類,只是為了存盤一個值:
public class RefTest{
private int value;
public void setValue(int value){
this.value = value;
}
public int getValue(){
return value;
}
}
并希望 RefTest b 始終是雙 RefTest a,我該怎么做?目前我的值相等:
RefTest a = new RefTest();
a.setValue(5);
RefTest b = new RefTest();
b = a;
System.out.println("RefTest a: " a.getValue());
System.out.println("RefTest b: " b.getValue());
a.setValue(10);
System.out.println("RefTest a: " a.getValue());
System.out.println("RefTest b: " b.getValue());
但我不確定如何將 b 設定為 2 a,因為“b = 2 a”回傳錯誤(如預期的那樣),并且 b.setValue(2*a.getValue()) 在 a 時不會更新.setValue() 改變。
uj5u.com熱心網友回復:
您希望完成的事情無法按照您實施的方式完成RefTest
您希望 a 和 b 表現不同的事實意味著它們實際上不能是同一個RefTest物件。
雖然要求有點奇怪,但從參考的角度來看,您需要實際存盤對物件的參考(在本例中為 a),而不是不是參考的 int 值(該值是在您呼叫時計算和設定的設定值)。您仍然需要做其他作業以實際確保您的 getValue 始終是值 a 的兩倍。
您需要實際定義兩個單獨的物件,其中“b”的行為將是變數(可以是對另一個物件的參考),如果它的 intValue 是該值的兩倍
如果您是 Java 新手,請查看 int 和實體變數中的物件參考之間的區別,以及組合之類的模式(在這種情況下可以幫助您)
uj5u.com熱心網友回復:
將您的定義RefTest視為給定,定義另一個類,如:
public class RefTestMultiple{
private RefTest source;
private int multiplier;
RefTestMultiple(RefTest source, int multiplier) {
this.source = source;
this.multiplier = multiplier;
}
public int getValue() {
return multiplier * source.getValue();
}
你可以像這樣使用它:
RefTest a = new RefTest();
RefTestMultiple b = new RefTestMultiple(a,2);
a.setValue(5);
System.out.println(b.getValue());
uj5u.com熱心網友回復:
我不認為 b = a 正在做你認為它正在做的事情。你想要的是:
b.setValue(a.getValue());
對于 b = 2a 你想要的是:
b.setValue(2 * a.getValue());
事實上,當 a 的值發生變化時,b 的值不會更新。這不是數學,這些是程式運算式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/435804.html
