Object中的clone()


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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值