Re: [問題] 一個關於reference的問題...
簡單來說,你所替換掉的只有 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
討論串 (同標題文章)
完整討論串 (本文為第 2 之 2 篇):
java 近期熱門文章
PTT數位生活區 即時熱門文章