对象的深浅克隆

1、

package cn.itcast.copy;
/*
 对象的克隆
     
     对象的浅克隆:
     
     对象浅克隆要注意的细节: 
         1. 如果一个对象需要调用clone的方法克隆,那么该对象所属的类必须要实现Cloneable接口。
         2. Cloneable接口只不过是一个标识接口而已,没有任何方法。
         3. 对象的浅克隆就是克隆一个对象的时候,如果被克隆的对象中维护了另外一个类的对象,这时候只是克隆另外一个对象的地址,而没有把
         另外一个对象也克隆一份。
         4. 对象的浅克隆也不会调用到构造方法的。
         
     对象的深克隆:

 */
public class Demo1 {
    
    
    public static void main(String[] args) throws Exception {
        Address address = new Address("广州");
        Person p1 = new Person(110,"狗娃",address);
        Person p2 = (Person) p1.clone(); //clone() 克隆了一个对象。
        
        p2.name = "狗剩";
        p2.address.city ="长沙";
        System.out.println("p1:"+p1);//长沙
        System.out.println("p2:"+ p2);//长沙
} }

2、

/*
对象的深克隆: 对象的深克隆就是利用对象的输入输出流把对象先写到文件上,然后再读取对象的
信息这个过程就称作为对象的深克隆。
    
    ObjectInputStream
    ObjectOutputStream 

 */
public class Demo2 {

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Address address = new Address("广州");
        Person p1 = new Person(110,"狗娃",address);
        writeObj(p1);
        Person p2  =readObj();
        
        p2.address.city = "长沙";
        System.out.println("p1:"+ p1);//广州
        System.out.println("p2:"+ p2);//长沙} 
//再从文件中读取对象的信息
public static Person readObj() throws ClassNotFoundException, IOException{

FileInputStream fileInputStream = new FileInputStream("F:\\obj.txt");
//创建对象的输入流对象 
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
return (Person) objectInputStream.readObject(); }

//先要把对象写到文件上。

public static void writeObj(Person p) throws IOException{

//建立一个文件 的输出流对象
FileOutputStream fileOutputStream = new FileOutputStream("F:\\obj.txt");

//建立对象的输出流
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);

//把对象写出
objectOutputStream.writeObject(p);

//关闭资源

objectOutputStream.close(); } }

3、person类

package cn.itcast.copy;

import java.io.Serializable;

class Address implements Serializable{
    
    String city;
        
    public Address(String city){
        this.city = city;
    }
    
}



public class Person implements Cloneable,Serializable {
    
    int id;
    
    String name;
    
    Address address;

    public Person(int id, String name) {
        this.id = id;
        this.name = name;
        
    }
    
    
    
    
    public Person(int id, String name, Address address) {
        this.id = id;
        this.name = name;
        this.address = address;
        System.out.println("=======构造方法调用了===");
    }

    @Override
    public String toString() {
        return "编号:"+ this.id+" 姓名:"+ this.name+" 地址:"+ address.city;
    }
    
    
    @Override
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

}

 

posted on 2016-11-22 22:26  hgfs瑞  阅读(268)  评论(0编辑  收藏  举报

导航