What is the clone method in Java?
Imagine that you've created an object in Java, complete with all its member functions and data members. Now, you are faced with a dilemma. You need an exact copy of this object, with all its properties intact, but you do not want to waste precious time and effort rewriting the entire code from scratch. That's where the clone() method in Java swoops in and saves the day!
The clone() method in Java is a part of the Cloneable interface and is used to create a copy, or clone, of an object. It provides a convenient way to duplicate an object's state without the need for manual field-by-field copying.
Syntax
protected Object clone() throws CloneNotSupportedException
Parameters
The clone() does not take parameters.
Return Type
The
clone()method in Java returns a copy of the object.If the object does not implement the Cloneable interface, it will throw
CloneNotSupportedException.Additionally, since the clone method is protected, it needs to be
overriddenin order to use it.
Example
Here's an example code snippet that demonstrates the usage of the clone() method
class Person implements Cloneable {private String name;private int age;public Person(String name, int age) {this.name = name;this.age = age;}// copy using clone() methodpublic Person clone() throws CloneNotSupportedException {return (Person) super.clone();}/*** Get the name of the person.** @return The name of the person.*/public String getName() {return name;}/*** Get the age of the person.** @return The age of the person.*/public int getAge() {return age;}public static void main(String[] args) {Person person1 = new Person("Alice", 25);try {// Cloning the person objectPerson person2 = person1.clone();// Modifying the cloned object's fieldsperson2.name = "Bob";person2.age = 30;// Outputting the state of both objectsSystem.out.println("Person 1 - Name: " + person1.getName() + ", Age: " + person1.getAge());System.out.println("Person 2 - Name: " + person2.getName() + ", Age: " + person2.getAge());} catch (CloneNotSupportedException e) {e.printStackTrace();}}}
Explanation
Lines 1–3: The
Personclass is defined and implements theCloneableinterface for object cloning. It contains private fieldsnameandage.Lines 5–8: The constructor initializes the
nameandagefields when aPersonobject is created.Lines 11–13: The
clone()method overrides theObjectclass'sclone()method to enable cloning ofPersonobjects. It performs a copy usingsuper.clone().Lines 20–22: The
getName()method returns thenamefield value.Lines 29–31: The
getAge()method returns theagefield value.Lines 33–49: In the
main()method, aPersonobject namedperson1is created with the name Alice and age 25. It is then cloned toperson2using theclone()method. Thenameandagefields ofperson2are modified to Bob and 30, respectively. The states of both objects are printed to the console.
Advantages of the clone()method
It allows two objects to exist independently, despite being copies of one another.
Cloning is the fastest way to copy objects.
Copy constructor copies all the data over explicitly. However, cloning copies data automatically.
Free Resources