Monday, 17 December 2007

object and reference

今天在书上看到一个这样的例子

class Number {
int i;
}
public class Assignment {
public static void main(String[] args) {
Number n1 = new Number();
Number n2 = new Number();
n1.i = 9;
n2.i = 47;
System.out.println("1: n1.i: " + n1.i +
", n2.i: " + n2.i);
n1 = n2;
System.out.println("2: n1.i: " + n1.i +
", n2.i: " + n2.i);
n1.i = 27;
System.out.println("3: n1.i: " + n1.i +
", n2.i: " + n2.i);

}
}

我感觉最后打印出来的一行很奇怪, 为什么改变n1.i的值n2.i的值也自动变化了.
书上这样解释:

Changing the n1 object appears to change the n2 object as well! This is because both n1 and n2 contain the same reference, which is pointing to the same object. (The original reference that was in n1, that pointed to the object holding a value of 9, was overwritten during the assignment and effectively lost; its object will be cleaned up by the garbage collector.)

n1.i = n2.i 属于基本类型的传值, 不属于引用. 你改变 n1.i的值是不会影响到 n2.i的.

关于对象的引用我还是有点晕哦...

No comments:

About Me

My photo
It is a nice blog, isn't it?