Java中对象克隆的用途是什么?
对象克隆是一种创建对象的精确副本的方法。 为此,可以使用对象类的clone() 方法来克隆对象。该Cloneable的 接口必须由一个类,其对象克隆创建实施。如果我们不实现Cloneable接口,则clone()方法将生成CloneNotSupportedException。
该clone()方法节省了用于创建对象的精确副本的额外处理任务。如果使用new关键字执行此操作,则将需要执行大量处理,因此可以使用对象克隆。
语法
protected Object clone() throws CloneNotSupportedException
示例
public class EmployeeTest implements Cloneable {
int id;
String name = "";
Employee(int id, String name) {
this.id = id;
this.name = name;
}
public Employee clone() throws CloneNotSupportedException {
return (Employee)super.clone();
}
public static void main(String[] args) {
Employee emp = new Employee(115, "Raja");
System.out.println(emp.name);
try {
Employee emp1 = emp.clone();
System.out.println(emp1.name);
} catch(CloneNotSupportedException cnse) {
cnse.printStackTrace();
}
}
}输出结果
Raja Raja