Java 深复制,浅复制

来源:互联网 发布:linux开端口命令 编辑:程序博客网 时间:2024/05/20 19:29

浅复制代码实例:

public class CloneTest1
{
public static void main(String[] args) throws CloneNotSupportedException
{
Student student  = new Student();

student.setAge(20);
student.setName("zhangsan");

Student student2 = (Student)student.clone();

System.out.println(student2.getAge());
System.out.println(student2.getName());
System.out.println("---------------");

student2.setName("lisi");

System.out.println(student.getName());
System.out.println(student2.getName());
}
}


class Student implements  Cloneable 
{
private int age;

private String name ;


public int getAge()
{
return age;
}


public void setAge(int age)
{
this.age = age;
}


public String getName()
{
return name;
}


public void setName(String name)
{
this.name = name;
}

@Override
public Object clone() throws CloneNotSupportedException
{
Object object = super.clone();  //浅复制

return object ;
}
}

深复制的小实例



public class CloneTest2
{
public static void main(String[] args) throws CloneNotSupportedException
{
Teacher teacher = new Teacher();

teacher.setAge(40);
teacher.setName("teacher zhang");

Student2 s1 = new Student2();

s1.setAge(20);
s1.setName("zhangsan");
s1.setTeacher(teacher);

Student2 s2 = (Student2)s1.clone();

System.out.println(s2.getName());
System.out.println(s2.getAge());

teacher.setName("teacher li");

System.out.println(s2.getTeacher().getName());
System.out.println(s2.getTeacher().getAge());

}
}


class Teacher implements Cloneable
{
private int age;

private String name;


public int getAge()
{
return age;
}


public void setAge(int age)
{
this.age = age;
}


public String getName()
{
return name;
}


public void setName(String name)
{
this.name = name;
}

@Override
public  Object clone() throws CloneNotSupportedException
{
Object object = super.clone();

return (Teacher)object;
}


}




class Student2 implements Cloneable
{
private int age;

private String name;

private Teacher teacher;


public int getAge()
{
return age;
}


public void setAge(int age)
{
this.age = age;
}


public String getName()
{
return name;
}


public void setName(String name)
{
this.name = name;
}


public Teacher getTeacher()
{
return teacher;
}


public void setTeacher(Teacher teacher)
{
this.teacher = teacher;
}


@Override
public Object clone() throws CloneNotSupportedException
{
Student2 student2 = (Student2)super.clone();

student2.setTeacher((Teacher)student2.getTeacher().clone());


return student2;
}


}



使用序列化的方式也可以实现对象的深复制





0 0
原创粉丝点击