在为对象“赋值”的时候,情况却发生了变化。对一个对象进行操作时,我们真正操作
的是对对象的引用。所以倘若“将一个对象赋值给另一个对象”,实际是将“引用”从一个
地方复制到另一个地方。这意味着假若对对象使用“c=d”,那么c和d都指向原本只有d
指向的那个对象。下面这个例子将向大家阐示这一点。
//: c03:Assignment.java
// Assignment with objects is a bit tricky.
import com.bruceeckel.simpletest.*;
class Number {
int i;
}
public class Assignment {
static Test monitor = new Test();
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);
monitor.expect(new String[] {
"1: n1.i: 9, n2.i: 47",
"2: n1.i: 47, n2.i: 47",
"3: n1.i: 27, n2.i: 27"
});
}
} ///:~