看板 java 關於我們 聯絡資訊
※ 引述《vencil (vencs)》之銘言: : 另外我還想問的問題就是 : private static Distance newDistance(Distance a){ : a = new Distance(a.getD() - 1); : return a; : } : 像上述的程式碼這樣,對於物件的修改要怎麼樣才會產生或不產生影響? 這個部分嚴格來說要了解 l-value/r-value 的分別。 對純 Java programmer 來說,至少要清楚 operator=(assignment) 的目標。 就 a = new Distance(a.getD() - 1); 來說,operator= 所作用的是變數 a 本身(變數本身所使用的空間),而跟 a 所持有 的值無關。也就是說此 statement 的 side effect 跟 a 的值所參考的 object 無關(a 也可能不參考任何物件)。 假如 class: Distance 有個 accessible field: unit, private static Distance newDistance(Distance a){ a.unit = ...; return a; } 此時 operator= 是作用在 a 變數的值所參考的物件的某個 field(field 所佔據的 空間),於是 newDistance method 的 side effect 就會出現在 a 所參考的 物件上(if any)。 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 218.173.142.250
vencil:終於看懂了  感謝說明 08/21 21:54