[問題] 一個關於reference的問題...
這是上課時, 老師提供的範例
要執行的程式碼如下
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
12/04 16:50, 1F
討論串 (同標題文章)
完整討論串 (本文為第 1 之 2 篇):
java 近期熱門文章
PTT數位生活區 即時熱門文章