深层克隆和浅层克隆

来源:互联网 发布:横道图用什么软件编制 编辑:程序博客网 时间:2024/05/29 09:01

深层克隆和浅层克隆

浅层克隆

仅仅克隆所考虑的对象,不克隆对象所引用的对象。下面的Student类没有引用其他类自然也不存在深层克隆。被克隆的类必须实现Cloneable接口。

public class student implements Cloneable{    String name;    int age;    student(String name,int age){        this.name=name;        this.age=age;    }    public Object clone(){        student stu=null;        try{            stu=(student)super.clone();//Object 中的clone()识别出你要复制的对象。        }catch(CloneNotSupportedException e){            System.out.println(e.toString());        }    return stu;    } }

深层克隆

不仅克隆所考虑的对象,还克隆对象所引用的对象(类属性)。下面的professor类引用了student类,存在聚合关系,在实现clone()方法的时候我对它的属性student也进行了克隆。

public class professor implements Cloneable {    String name;    int age;    student student;    professor(String name, int age,student student) {        this.name = name;        this.age = age;        this.student=student;    }    public Object clone() {        professor p=null;        try {            p=(professor)super.clone();            p.student=(student)this.student.clone();        } catch (CloneNotSupportedException e) {            System.out.println(e.toString());        }        return p;    }}

testDemo:

public class testDemo {    public static void main(String[] args){        student s1 = new student("wsl", 21);        student s2 = (student) s1.clone();        s2.name = "xm";        s2.age = 20;        // 修改学生2后,不影响学生1的值。        System.out.println("name=" + s1.name + "," + "age=" + s1.age);        System.out.println("name=" + s2.name + "," + "age=" + s2.age);        professor p1=new professor("tim", 42, s1);        professor p2=(professor)p1.clone();        System.out.println("name=" + p1.name + "," + "age=" + p1.age+","+"student"+p1.student);        System.out.println("name=" + p2.name + "," + "age=" + p2.age+","+"student"+p2.student);    }}

打印结果:
name=wsl,age=21
name=xm,age=20
name=tim,age=42,studentclone.student@15db9742
name=tim,age=42,studentclone.student@6d06d69c
可以看到后两行输出的字符串不同,说明student也被克隆了。

原创粉丝点击