作者darkk6 (Mr. Pan)
看板java
標題Re: [問題] 一個關於reference的問題...
時間Wed Dec 4 13:53:06 2013
簡單來說,你所替換掉的只有 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
1F:推 marketcos:真的是非常謝謝! 弄清楚了 12/06 17:07