import java.text.SimpleDateFormat;
import java.util.Date;
public class Test {
public static void main(String[] args) throws CloneNotSupportedException {
Person p1 = new Person("Mels", new Date());
Person p2 = p1.clone();
System.out.println(p1);
System.out.println(p2);
}
}
class Person implements Cloneable
{
private String name;
private Date birthday;
public Person(String name, Date birthday) {
this.name = name;
this.birthday = birthday;
}
public Person clone() throws CloneNotSupportedException {
Person temp = (Person) super.clone();
temp.birthday = (Date) birthday.clone();
return temp;
}
public String toString() {
return "Name: " + name + " Birthday: "
+ new SimpleDateFormat("yyyy-MM-dd").format(birthday);
}
}
1、clone()是Object中的一个protected方法
2、Object没有实现Cloneable接口
3、Cloneable中没有clone()方法
4、要用clone()必须implements Cloneable
5、应该重写clone()方法,否则就是"shallow" copy,只是讲值拷贝过去,要是field里面有reference type就有可能
出错(因为有可能共享数据),但如果field 是immutable的就不会,比如String
6、就算你的class不需要做deep copy,you still need to implement the Cloneable interface,
redefine clone to be public