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

看板java作者 (marketcos)時間11年前 (2013/12/04 13:43), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串1/2 (看更多)
這是上課時, 老師提供的範例 要執行的程式碼如下 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); System.out.println("s2 BEFORE calling tryToReplace: "); s2.writeOutput( ); s1.tryToReplace(s2); System.out.println("s2 AFTER calling tryToReplace: "); s2.writeOutput( ); s1.change(s2); System.out.println("s2 AFTER calling change: "); s2.writeOutput( ); } } --------------------------------------------------------------------- DemoSpecies類別如下: public class DemoSpecies { private String name; private int population; private double growthRate; /** Tries to set intVariable equal to the population of the calling object. But arguments of a primitive type cannot be changed. */ public void tryToChange(int intVariable) { intVariable = this.population; } /** Tries to make otherObject reference the calling object. But arguments of a class type cannot be replaced. */ public void tryToReplace(DemoSpecies otherObject) { otherObject = this; } 另外還有 writeOutput( )是印出物件的內容, 在此省略, 以免篇幅過長 --------------------------------------------------------------------- 輸出結果為: s2 BEFORE calling tryToReplace: Name = Ferengie Fur Ball Population = 90 Growth rate = 56.0% s2 AFTER calling tryToReplace: Name = Ferengie Fur Ball Population = 90 Growth rate = 56.0% s2 AFTER calling change: Name = Klingon Ox Population = 10 Growth rate = 15.0% --------------------------------------------------------------------- 我不解的地方是... 為什麼 s2 AFTER calling tryToReplace: Name = Ferengie Fur Ball Population = 90 Growth rate = 56.0% 我以為在 s1.tryToReplace(s2); 之後 s1 = s2 s1和s2會指向同一組資料 所以s2應該會是... Name = Klingon Ox Population = 10 Growth rate = 15.0% 希望先進們可以幫忙解釋一下這裡reference的問題 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 141.70.6.9

12/04 16:50, , 1F
因為int是native 是call by value 你該用Integer
12/04 16:50, 1F
文章代碼(AID): #1Idi3a6- (java)
文章代碼(AID): #1Idi3a6- (java)