作者marketcos (marketcos)
看板java
标题[问题] 一个关於reference的问题...
时间Wed Dec 4 13:42:57 2013
这是上课时, 老师提供的范例
要执行的程式码如下
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
1F:推 Killercat:因为int是native 是call by value 你该用Integer 12/04 16:50