public class Test { /** * * @param args * @throws CloneNotSupportedException */ public static void main(String[] args) throws CloneNotSupportedException { // TODO Auto-generated method stub testReference(); } /** * 测试引用传递 * @throws CloneNotSupportedException */ public static void testReference() throws CloneNotSupportedException { Node node = new Node(10, 1); Node a = node; Node b = node; System.out.println("this is a : " + a); System.out.println("this is b : " + b); a.data = 20;//修改 System.out.println("\nafter modification:\n"); //由于是引用传递,实际上只有a修改了,b也会跟着修改,因为a和b引用的是同一个对象 System.out.println("this is a : " + a); System.out.println("this is b : " + b); System.out.println("============== test clone =============="); /** * 需要注意的是,此时a和b不再引用同一个对象了 * a指向的是以node为模板,克隆出来的一个新的Node实例 * b指向的依然是原来的node */ a = (Node) node.clone(); b = node; System.out.println("this is a : " + a); System.out.println("this is b : " + b); a.data = 30;//修改 System.out.println("\nafter modification:\n"); System.out.println("this is a : " + a); System.out.println("this is b : " + b); } } class Node implements Cloneable{ int data; int no; public Node(int data, int no) { super(); this.data = data; this.no = no; } @Override public String toString() { return "Node [data=" + data + ", no=" + no + "]"; } @Override public Object clone() throws CloneNotSupportedException { // TODO Auto-generated method stub Node node = new Node(data, no); return node; } }
打印结果如下:
this is a : Node [data=10, no=1] this is b : Node [data=10, no=1] after modification: this is a : Node [data=20, no=1] this is b : Node [data=20, no=1] /** 注意,此时虽然只修改了a.data,但是实际上b.data的值和a.data的值一起改变 因为a和b引用的是同一个对象 */ ============== test clone ============== /** a指向了克隆后的对象,b仍然指向原来的对象 */ this is a : Node [data=20, no=1] this is b : Node [data=20, no=1] after modification: /** 此时修改a和修改b已经无关了,因为a和b指向的不是同一个对象 因此a修改a.data=30时,并不会影响b.data */ this is a : Node [data=30, no=1] this is b : Node [data=20, no=1]