Home > Java > javaTutorial > body text

What is the use of object cloning in Java?

WBOY
Release: 2023-08-30 15:17:03
forward
1254 people have browsed it

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
Copy after login

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

Output

Raja
Raja
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!