Java 中,在对一个对象进行操作如赋值,传参时,实际上操作的是对象的引用。这就是“别名现象”。
class Test {
int value;
}
public class Operator {
public static void f(Test t) {
t.value = 10;
}
public static void main(String[] args) {
Test t1 = new Test();
Test t2 = new Test();
t1.value = 1; //t1, t2 指向不同对象
t2.value = 2;
System.out.println("---------- Initial value ----------");
System.out.println("t1.value = " + t1.value);
System.out.println("t2.value = " + t2.value);
System.out.println("---------- t1 refer to t2 ----------");
t1 = t2; //t1 指向t2 所指的对象
System.out.println("t1.value = " + t1.value);
System.out.println("t2.value = " + t2.value);
System.out.println("---------- Change t2's value ----------");
t2.value = 3; //改变t2 将影响t1
System.out.println("t1.value = " + t1.value);
System.out.println("t2.value = " + t2.value);
System.out.println("---------- Pass t1 to f() and change value ----------");
f(t1); //将对象作为参数传递的也是该对象的引用
System.out.println("t1.value = " + t1.value);
System.out.println("t2.value = " + t2.value);
}
}
输出结果:
---------- Initial value ----------
t1.value = 1
t2.value = 2
---------- t1 refer to t2 ----------
t1.value = 2
t2.value = 2
---------- Change t2's value ----------
t1.value = 3
t2.value = 3
---------- Pass t1 to f() and change value ----------
t1.value = 10
t2.value = 10
Java 对于对象的这种特性很基础但很重要。