java浅拷贝的格式:
<pre name="code" class="java">public class A implements Cloneable{
public Object clone(){
try{
return super.clone();
}
catch(CloneNotSupportedException e){
return null;
}
}
……
}
深拷贝
public class A implements Cloneable{
public Object clone(){
try{
A copy = (A)super.clone();
copy.mutable = (mutable 类型)mutable.clone();
return copy;
}
catch(CloneNotSupportedException e){
return null;
}
}
……
}
如下我建立了一个Employee类。
package Employee;
import java.util.Date;
import java.util.GregorianCalendar;
public class Employee implements Cloneable{
public Object clone(){
try{
//Employee copy = (Employee)super.clone();
//copy.hireday = (Date) hireday.clone();
//return copy;
return super.clone();
}
catch(CloneNotSupportedException e){
return null;
}
}
public Employee(String name,int salary) {
this.name = name;
this.salary = salary;
//this.hireday = new GregorianCalendar(year,month-1,day).getTime();
}
public void setName(String name){
this.name = name;
}
public void setHireday(int year,int month,int day){
this.hireday = new GregorianCalendar(year,month-1,day).getTime();
}
public void raiseSalary(double percent){
salary = salary * (1 + percent/100);
}
public String getName(){
return this.name;
}
public double getSalary(){
return this.salary;
}
public Date getHireday(){
return this.hireday;
}
private String name;
private double salary;
private Date hireday;
}
主函数是:
package Employee;
public class Main {
public static void main(String[] args) {
Employee John = new Employee("John",10000);
John.setHireday(2016,3,18);
Employee copyJohn = (Employee)John.clone();
John.setHireday(2015,1,1);
John.raiseSalary(100);
System.out.println("原类的招聘时间:"+John.getHireday());
System.out.println("克隆类的招聘时间"+copyJohn.getHireday());
System.out.println("原类的工资: "+John.getSalary());
System.out.println("克隆类的工资:"+copyJohn.getSalary());
}
}
按理说这是一个浅拷贝,应该会返回null,但是返回结果如下:
不是很明白。