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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP