Java 中的对象克隆有什么用?

javaobject oriented programmingprogramming更新于 2024/7/26 3:28:00

对象克隆是一种创建对象精确副本的方法。为此,对象类的 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

相关文章