Re: [問題] 一個關於reference的問題...

看板java作者 (Mr. Pan)時間11年前 (2013/12/04 13:53), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串2/2 (看更多)
簡單來說,你所替換掉的只有 tryToReplace 方法中 otherObject 變數所指向的物件而已,不影響 main 裡面的 s1 和 s2 : public class ParametersDemo : { : public static void main(String[] args) : { : DemoSpecies s1 = new DemoSpecies( ), : s2 = new DemoSpecies( ); : s1.setSpecies("Klingon Ox", 10, 15); : s2.setSpecies("Ferengie Fur Ball", 90, 56); : s1.tryToReplace(s2); : } : } : public class DemoSpecies : { : public void tryToReplace(DemoSpecies otherObject) : { // 在這邊 otherObject == s2 : otherObject = this; // 到這邊 otherObject == s1 : } : } 無論怎麼更變,充其量也只有替換掉 tryToReplace 中這個 otherObject 所指向的 obejct ,不影響 main 中的 s1 , s2 也就是所做的只有將底下綠色的部分變成黃色: s1 ────┐ │ ↓ DemoSpecies No.1 ←──────┐ otherObject ( in s1 tryToReplace ) DemoSpecies No.2 ←──────┘ ↑ │ s2 ────┘ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 1.174.231.16

12/06 17:07, , 1F
真的是非常謝謝! 弄清楚了
12/06 17:07, 1F
文章代碼(AID): #1IdiD5Jp (java)
文章代碼(AID): #1IdiD5Jp (java)