import java.util.*;
public class CloneTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Employee original = new Employee("John Q,publi c", 5000);
original.setHireDay(2000, 1, 1);
Employee copy = original.clone();
copy.raiseSalary(10);
copy.setHireDay(2002, 12, 31);
System.out.println("original=" + original);
System.out.println("copy+" + copy);
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
//Cloneable 仅作为 clone 接口的标记,表明类设计者知道要进行克隆处理
//标记接口
class Employee implements Cloneable{
public Employee(String n, double s) {
name = n;
salary = s;
hireDay = new Date();
}
public Employee clone() throws CloneNotSupportedException {
//使用Object.clone方法时如果对象中的所有数据域都属于数值类型和基本类型,则所有拷贝没问题
//但如果在对象中包含了子对象的引用,拷贝结果会使得两个域引用同一个子对象,因此原始对象和克隆对象共享这些信息
Employee cloned = (Employee) super.clone();
//为了实现深拷贝,鼻血克隆所有肯变的实例域
cloned.hireDay = (Date) hireDay.clone();
return cloned;
}
public void setHireDay(int year, int month, int day) {
Date newHireDay = new GregorianCalendar(year, month - 1, day).getTime();
hireDay.setTime(newHireDay.getTime());
}
public void raiseSalary(double byPercent) {
double raise = salary * byPercent / 100;
salary += raise;
}
public String toString() {
return "Employee[name=" + name + ",salary=" + salary + ",hireDay=" + hireDay + "]";
}
private String name;
private double salary;
private Date hireDay;
}
public interface Cloneable此类实现了 Cloneable 接口,以指示 Object.clone() 方法可以合法地对该类实例进行按字段复制。
如果在没有实现 Cloneable 接口的实例上调用 Object 的 clone 方法,则会导致抛出 CloneNotSupportedException 异常