首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

一个深复制事例

2012-12-18 
一个深复制例子这是改的一个例子(关于深复制:连同该对象的引用一起复制):?class Professor implements Clo

一个深复制例子

这是改的一个例子(关于深复制:连同该对象的引用一起复制):

?

class Professor implements Cloneable{    String name;    int age;    Professor(String name,int age)    {        this.name=name;        this.age=age;    }    public Object clone()    {        Professor o=null;        try        {            o=(Professor)super.clone();        }        catch(CloneNotSupportedException e)        {            System.out.println(e.toString());        }        return o;    }}class Student implements Cloneable{    String name;    int age;    Professor p;    Student(String name,int age,Professor p)    {        this.name=name;        this.age=age;        this.p=p;    }    public Object clone()    {        Student o=null;        try        {            o=(Student)super.clone();            o.p=(Professor)p.clone();        }        catch(CloneNotSupportedException e)        {            System.out.println(e.toString());        }                return o;    }}public class DeepClone{    public static void main(String[] args)    {      Professor p=new Professor("wangwu",50);      Student s1=new Student("zhangsan",18,p);      Student s2=(Student)s1.clone();      s2.p.name="lisi";      s2.p.age=30;      System.out.println("name="+s1.p.name+","+"age="+s1.p.age);    }}
?

下面是同样例子的浅复制(复制体中的引用和原体中的引用相同,指向同一内存地址):

class Professor{    String name;    int age;    Professor(String name,int age)    {        this.name=name;        this.age=age;    }}class Student implements Cloneable{    String name;    int age;    Professor p;    Student(String name,int age,Professor p)    {        this.name=name;        this.age=age;        this.p=p;    }    public Object clone()    {        Student o=null;        try        {            o=(Student)super.clone();        }        catch(CloneNotSupportedException e)        {            System.out.println(e.toString());        }                return o;    }}public class ShallowClone{    public static void main(String[] args)    {      Professor p=new Professor("wangwu",50);      Student s1=new Student("zhangsan",18,p);      Student s2=(Student)s1.clone();      s2.p.name="lisi";      s2.p.age=30;      System.out.println("name="+s1.p.name+","+"age="+s1.p.age);    }}
?

?

热点排行