实例对象的clone
对于八种基本数据类型clone则比较简单:
int m=10;
int n=m;
这样就可以实现基本数据类型的clone,但是实例对象就不可以,因为上述操作对象,只是两个变量都指向同一个对象,因此通过任何一个变量来修改对象,另一方都会察觉。
而有时候需要对一个实例对象进行Clone,用来保存其状态,那么就需要专门的操作来实现对象的Clone,这样Clone以后,对原有的实例对象进行修改,则不会影响Clone的对象,因此可以用Clone的对象来保存其当时的状态。
主要有两种方式:
》继承Cloneable接口并重写Object中clone()方法
》继承Serializable接口来表示可序列化,同时自己写一个clone方法,通过对象的序列化和反序列化来实现clone
重写clone方法:
/*
Creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object.
The general intent is that, for any object x, the expression:
1) x.clone() != x will be true
2) x.clone().getClass() == x.getClass() will be true, but these are not absolute requirements.
3) x.clone().equals(x) will be true, this is not an absolute requirement.
*/
protected native Object clone() throws CloneNotSupportedException;
-浅克隆
public class ShallowClone implements Cloneable {
String name="请clone我!";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
protected Object clone(){
// TODO Auto-generated method stub
ShallowClone SC=null;
try {
SC=(ShallowClone)super.clone();
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return SC;
}
public static void main(String[] args) {
ShallowClone SC=new ShallowClone();
System.out.println("-----------原版-----------");
System.out.println(SC.getName());
ShallowClone SClone=(ShallowClone)SC.clone();
System.out.println("-----------克隆版-----------");
System.out.println(SClone.getName());
System.out.println("------区别是不是两个对象---------");
System.out.println("原版:"+SC.getName());
SClone.setName("我是Clone的!");
System.out.println("克隆版:"+SClone.getName());
System.out.println("----------两个对象是地址是否相等------------"