深浅克隆概念:
(1)浅克隆(浅复制):被克隆对象的所有变量都含有与原来的对象相同的值,而所有的对其它对象的引用仍然指向原来的对象。也就是说,浅克隆仅仅是克隆所要考虑的对象,而不克隆她所引用的对象。、
(2)深克隆(深复制):被复制对象的所有变量都含有与他原来对象相同的值,但有些引用其它对象的变量除外。因为那些引用其它对象的变量将指向他被复制过的新对象,而不是原有的那些被引用的对象。也就是说,深克隆把要克隆要引用的对象都克隆了一遍。
(1)Lady 类
package clone;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Date;
/**
* @author Administrator
*
*/
public class Lady implements Cloneable,Serializable{
private static final long serialVersionUID = 1L;
private String name;
private int age;
private Date birthDate;
private Pet pet;
//构造函数;
public Lady() {
name="nks";
age=23;
this.birthDate = new Date();
pet =new Pet();
}
//克隆
public Object clone(){
Lady temp=null;
try {
/**浅克隆 */
temp=(Lady)super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return temp;
}
public Object fuzhiClone() throws IOException, ClassNotFoundException{
//实现一个输出流
ByteArrayOutputStream by=new ByteArrayOutputStream();
ObjectOutputStream oos=new ObjectOutputStream(by);
//writeObject 方法用于将对象写入流中
oos.writeObject(this);
//实现一个输入流
ByteArrayInputStream bin=new ByteArrayInputStream(by.toByteArray());
ObjectInputStream oin= new ObjectInputStream(bin);
//readObject 方法用于从流读取对象
return oin.readObject();
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getBrithDate() {
return birthDate;
}
public void setBrithDate(Date brithDate) {
this.birthDate = brithDate;
}
public Pet getPet() {
return pet;
}
public void setPet(Pet pet) {
this.pet = pet;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
}
(2)Pet 类
package clone;
import java.io.Serializable;
public class Pet implements Serializable{
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
(3)Test 测试类
package clone;
import java.io.IOException;
/**
* @author Administrator
*
*/
public class Test
{
private Lady lady=new Lady();
private Lady fuzhilady;
public void bianhua() throws IOException, ClassNotFoundException{
Lady fuzhilady=(Lady) lady.fuzhiClone();
System.out.println("本身的生日是:" + lady.getBrithDate());
System.out.println("克隆的生日是:" + fuzhilady.getBrithDate());
System.out.println("本身跟克隆是否为同一个对象 " + (lady == fuzhilady));
System.out.println("本身拥有的Pet 跟 克隆拥有的Pet是否为同一个对象? "
+ (lady.getPet()== fuzhilady.getPet()));
}
/**
* @param args
* @throws ClassNotFoundException
* @throws IOException
*/
public static void main(String[] args) throws IOException, ClassNotFoundException {
Test te=new Test();
te.bianhua();
}
}