对象引用与对象克隆
对象克隆就是在原先对象的基础上,再复制一份,克隆的属性与原先的一模一样,但是是两个对象,之后对这两个对象的任何操作都不会影响到对方。要想将某个对象克隆,必须实现Cloneable接口,然后还需要复写Object类的clone方法。
对象引用其实是多个索引对同一个对象的引用,不管谁改变了对象的属性,对象都会改变,其他索引再访问时,属性已经变了
像函数式编程,对象的操作都是无副作用的,不会改变对象的状态,类似于对象克隆,就是把对象再复制一份,原先的对象不动,只需要使用复制的那个对象即可。而原始的java语法,大多数都会改变对象的状态,这一点需要注意。
下面看一个简单的实例:
public class TestObj implements Cloneable{ private String name; private String address; private Integer age; TestObj(){ } public TestObj(String name, String address, Integer age){ this.name = name; this.address = address; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "TestObj [name=" + name + ", address=" + address + ", age=" + age + "]"; } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } }
public class Clone { public static void main(String[] args) throws CloneNotSupportedException { TestObj t1 = new TestObj("tom","beijing",12); TestObj t2 = t1; TestObj t1Clone = (TestObj) t1.clone(); /*其实是两个对象实例,原对象被两个引用指向,另一个是克隆对象*/ System.out.println(t1);//TestObj [name=tom, address=beijing, age=12] System.out.println(t2);//TestObj [name=tom, address=beijing, age=12] System.out.println(t1Clone);//TestObj [name=tom, address=beijing, age=12] /*因为两个索引都指向同一个对象,所以他们是相等的,而原对象与克隆的对象是两个对象,所以是不相当的*/ System.out.println(t1 == t2);//true System.out.println(t1 == t1Clone);//false System.out.println(); /*修改任何一个索引,原对象属性被改变,访问任何一个索引,对象都是已经被改变了的*/ t2.setName("jerry"); System.out.println(t1);//TestObj [name=jerry, address=beijing, age=12] System.out.println(t2);//TestObj [name=jerry, address=beijing, age=12] System.out.println(t1Clone);//TestObj [name=tom, address=beijing, age=12] System.out.println(); /*修改克隆对象的属性,不会影响原对象*/ t1Clone.setAge(234); System.out.println(t1);//TestObj [name=jerry, address=beijing, age=12] System.out.println(t2);//TestObj [name=jerry, address=beijing, age=12] System.out.println(t1Clone);//TestObj [name=tom, address=beijing, age=234] } }
本文来自博客园,作者:wzyy,转载请注明原文链接:https://www.cnblogs.com/wwzyy/p/5832159.html