clone方法
有个User类, 拥有字段String类型的name和Date类型的date, 有参构造,无参构造,重写toString方法,实现Cloneable接口,并重写clone方法
public class User implements Cloneable {
private String name;
private Date date;
public User() { }
public User(String name, Date date) {
this.name = name;
this.date = date;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Date getDate() { return date; }
public void setDate(Date date) { this.date = date; }
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", date=" + date +
'}';
}
}
产生一个User对象,再克隆它,测试一下两个对象内容是否相同,是否是同一个对象:
public class MyTest {
public static void main(String[] args) throws CloneNotSupportedException {
Date date = new Date();
User user1 = new User("居十方",date);
//克隆user1,产生user2
User user2 = (User) user1.clone();
System.out.println(user1);
System.out.println(user2);
//看看是不是同一个对象
System.out.println(user1==user2);
}
}
看来克隆出的对象确实是在堆中产生了一个新的对象, 至于内容那肯定是一样的,不然还怎么叫克隆呢
深克隆还是浅克隆?
修改user1的date对象, 观察user2的date属性是否变化:
public class MyTest {
public static void main(String[] args) throws CloneNotSupportedException {
Date date = new Date();
User user1 = new User("居十方",date);
User user2 = (User) user1.clone();
System.out.println(user1);
System.out.println(user2);
date.setTime(12345678);
System.out.println("===============================");
System.out.println(user1);
System.out.println(user2);
}
}
user2的date属性也发生了变化,看来clone方法克隆出的对象属于浅克隆
改造成深克隆:
@Override
protected Object clone() throws CloneNotSupportedException {
Object obj = super.clone();
//实现深克隆的操作
User user = (User)obj;
//将这个对象的属性也进行克隆
user.date= (Date) this.date.clone();
return obj;
}
改造成功, 现在是深克隆了