浅复制
import java.util.Date;
import java.util.GregorianCalendar;
class Employee implements Cloneable{
private String name;
private double salary;
private Date hireDay;
public Employee(String n, double s){
name = n;
salary = s;
hireDay = new Date();
}
public Employee clone() throws CloneNotSupportedException{
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+"]";
}
}
public class Main {
public static void main(String[] args) throws ClassNotFoundException {
try {
Employee original = new Employee("tom",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();
}
}
}
运行结果:
original=Employee[name=tom,salary=5000.0, hireDay=Tue Dec 31 00:00:00 CST 2002]
copy=Employee[name=tom,salary=5500.0, hireDay=Tue Dec 31 00:00:00 CST 2002]
深复制:
import java.util.Date;
import java.util.GregorianCalendar;
class Employee implements Cloneable{
private String name;
private double salary;
private Date hireDay;
public Employee(String n, double s){
name = n;
salary = s;
hireDay = new Date();
}
public Employee clone() throws CloneNotSupportedException{
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+"]";
}
}
public class Main {
public static void main(String[] args) throws ClassNotFoundException {
try {
Employee original = new Employee("tom",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();
}
}
}
运行结果:
original=Employee[name=tom,salary=5000.0, hireDay=Sat Jan 01 00:00:00 CST 2000]
copy=Employee[name=tom,salary=5500.0, hireDay=Tue Dec 31 00:00:00 CST 2002]