浅克隆:
class Student implements Cloneable{
public String sname;
public Date birthday;
public Student () {}
public Student (String sname, Date birthday) {
this .sname = sname;
this .birthday = birthday;
}
public String getSname () {
return sname;
}
public void setSname (String sname) {
this .sname = sname;
}
public Date getBirthday () {
return birthday;
}
public void setBirthday (Date birthday) {
this .birthday = birthday;
}
@Override
protected Object clone () throws CloneNotSupportedException {
Object obj= super.clone();
return obj;
}
}
Student s1=new Student("link" ,new Date(123456 ));
System.out .println(s1);
Student s2=(Student) s1.clone();
System.out .println(s2);
System.out .println(s1.sname==s2.sname);
System.out .println(s1.birthday==s2.birthday);
深克隆:
class Student implements Cloneable{
public String sname;
public Date birthday;
public Student () {}
public Student (String sname, Date birthday) {
this .sname = sname;
this .birthday = birthday;
}
public String getSname () {
return sname;
}
public void setSname (String sname) {
this .sname = sname;
}
public Date getBirthday () {
return birthday;
}
public void setBirthday (Date birthday) {
this .birthday = birthday;
}
@Override
protected Object clone () throws CloneNotSupportedException {
Object obj= super.clone();
Student s=(Student) obj;
s.sname=new String(this .getSname());
s.birthday=(Date) this .birthday.clone();
return obj;
}
}
Student s1=new Student("link" ,new Date(123456 ));
System.out .println(s1);
Student s2=(Student) s1.clone();
System.out .println(s2);
System.out .println(s1.sname==s2.sname);
System.out .println(s1.birthday==s2.birthday);