In Java, a clone object is a copy of an existing object. It is created using the clone() method, which is defined in the Object class and can be overridden in subclasses. When an object is cloned, a new instance of the same class is created with the same state as the original object.
It is important to note that not all classes in Java support cloning. In order for a class to be cloned, it must implement the Cloneable interface and override the clone() method to make it public. If a class does not do this, attempting to clone an object of that class will result in a CloneNotSupportedException being thrown.
Here's an example of how cloning works in Java:
public class Person implements Cloneable { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public Object clone() throws CloneNotSupportedException { return super.clone(); } public String getName() { return name; } public int getAge() { return age; } public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } }
In this example, the Person class implements the Cloneable interface and overrides the clone() method. This allows us to create a clone of a Person object like this:
Person person1 = new Person("John", 30); Person person2 = (Person) person1.clone();
After this code is executed, person1 and person2 will be two separate objects with identical state. Changes made to one object will not affect the other object.
For example:
person2.setName("Jane"); person2.setAge(25); System.out.println(person1.getName()); // Output: John System.out.println(person1.getAge()); // Output: 30 System.out.println(person2.getName()); // Output: Jane System.out.println(person2.getAge()); // Output: 25
In this code, we changed the name and age of person2, but person1 remained unchanged. This demonstrates how cloning can be used to create independent copies of an object.