一个深复制例子

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

 

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);
    }
}
 

 

你可能感兴趣的:(例子)