对象克隆,实现Cloneable接口中的clone方法,在方法中调用父类的clone方法克隆对象(浅克隆),
若对象中有其他对象属性,则调用其他对象的克隆方法克隆属性对象,并赋值给克隆对象(深克隆)。
下面给出浅克隆及深克隆的两种代码
浅克隆
public class Book
{
public String name
public Book (String name)
{
this.age=age;
this.name=name;
}
}
public class Student implements Clonable
{
public int age;
public String name;
public Book book;
public Student (int age,String name;Book book)
{
this.age=age;
this.name=name;
this.book=book;
}
public Object clone()
{
Student s = null;
try {
s= (Student)super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return s;
}
public static void main(String[] args)
{
Book book = new Book("English book");
Student s1 = new Student(20,"张三",book);
Student s2 = (Student) s1.clone();//克隆 对象s1
System.out.println(s1==s2);
System.out.println(s1.book==s2.book);
}
}
输出 false true 表示 s1 于s2 指向的不是同一个对象,s2时s1的克隆 s1.book与s2.book指向的是同一个对象 克隆了Student 未克隆Student的属性Book 克隆单个对象 是浅克隆
深克隆
public class Book implements Clonable
{
public String name
public Book (String name)
{
this.age=age;
this.name=name;
}
public Object clone()
{
Book s = null;
try {
s= (Book)super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return s;
}
}public class Student implements Clonable
{
public int age;
public String name;
public Book book;
public Student (int age,String name;Book book)
{
this.age=age;
this.name=name;
this.book=book;
}
public Object clone()
{
Student s = null;
try {
s= (Student)super.clone();
s.book=(Book)s.book.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return s;
}
public static void main(String[] args)
{
Book book = new Book("English book");
Student s1 = new Student(20,"张三",book);
Student s2 = (Student) s1.clone();//克隆 对象s1
System.out.println(s1==s2);
System.out.println(s1.book==s2.book);
}
}
输出 false false 表示 s1 于s2 指向的不是同一个对象,s2时s1的克隆 s1.book与s2.book指向的不是同一个对象 s1.book也克隆了 克隆了student的对象网 属于深克隆