Home  >  Article  >  Java  >  What is the use of object cloning in Java?

What is the use of object cloning in Java?

WBOY
WBOYforward
2023-08-30 15:17:031233browse

What is the use of object cloning in Java?

Object cloning is a method of creating an exact copy of an object. To do this, use the clone() method of the object class to clone the object. CloneableThe interface must be implemented by the class whose object clone is to be created. If we do not implement the Cloneable interface, the clone() method will generate CloneNotSupportedException.

The clone() method saves the extra processing of creating an exact copy. Purpose. If we use the new keyword to execute, a lot of processing will need to be performed, so we can use object cloning.

Syntax

protected Object clone() throws CloneNotSupportedException

Example

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();
      }
   }
}

Output

Raja
Raja

The above is the detailed content of What is the use of object cloning in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete