java_clone方法使用詳解

Pop_Rain發表於2017-06-29

核心實現程式碼

class Employee implements Cloneable
{
	private String name;
	private double salary;
	private Date hireDay;
	
	public Employee clone() throws CloneNotSupportedException
	{
		Employee o = (Employee)super.clone(); //Object.clone()
		o.hireDay = (Date)hireDay.clone();
		return o;
	}
}

兩點說明

1、clone方法實現要點:實現 Cloneable介面 + 使用public訪問修飾符重新定義clone方法以實現深拷貝

2、clone方法是Object類的一個protected方法,因此無法呼叫anObj.clone(),也就是說使用者在編寫的程式碼中不能直接呼叫它,只有Employee才能克隆Employee物件(這樣通過類來拷貝將避免出現淺拷貝的 問題)

3、Cloneable介面是java提供的幾個標記介面(tagging interface),與通常介面不同的是它沒有指定方法,Cloneable中的clone方法是從Object類繼承而來,這個Cloneable介面作為標記是想說明如果一個物件需要克隆而沒有實現Cloneable介面,就會產生一個異常。

完整示例程式

/**
 * This program demonstrates clone()
 */
import java.util.*;

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 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 per)
	{
		salary *= (1 + per/100);
	}
	
	public String toString()
	{
		return "Employee[name=" + name + ",salary=" + salary + ",hireDay=" + hireDay + "]";
	}
	
	public Employee clone() throws CloneNotSupportedException
	{
		Employee o = (Employee)super.clone(); //call Object.clone()
		o.hireDay = (Date)hireDay.clone();  //clone mutable fields
		return o;
	}
}

public class Test
{
	public static void main(String args[])
	{
		try
		{
			Employee t1 = new Employee("alice", 1000);
			t1.setHireDay(2000, 1, 1);
			Employee t2 = t1.clone();
			t2.raiseSalary(100);
			t2.setHireDay(2010, 1, 1);
			System.out.println(t1.toString());
			System.out.println(t2.toString());
		}
		catch(CloneNotSupportedException e)
		{
			e.printStackTrace();
		}
	}
}
output:

Employee[name=alice,salary=1000.0,hireDay=Sat Jan 01 00:00:00 CST 2000]
Employee[name=alice,salary=2000.0,hireDay=Fri Jan 01 00:00:00 CST 2010]

相關文章