Object cloning in Java

Object cloning in Java is the process of creating an exact copy or a clone of an object. Cloning allows you to create a new instance of an object with the same state as the original object, but with a separate memory location.


Java provides two ways to clone an object:


  1. 1. Shallow Copy: This is the default implementation of the clone() method in the Object class. A shallow copy creates a new object and copies all the field values of the original object to the new object. However, if the field is a reference to another object, the reference is copied, but the referred object is not. In other words, the new object will have a reference to the same object as the original object.


  2. 2. Deep Copy: A deep copy creates a new object and copies all the field values of the original object to the new object. However, if the field is a reference to another object, the reference is also copied, and a new object is created for the referred object. In other words, the new object will have a new copy of all the referenced objects in the original object.


Here's an example that demonstrates how to clone an object 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 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;
    }

    @Override
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

// Example usage
Person person1 = new Person("John", 30);
Person person2 = (Person) person1.clone();

// Shallow copy: person1 and person2 have the same reference to the name String object
System.out.println(person1.getName()); // John
System.out.println(person2.getName()); // John
person2.setName("Mike");
System.out.println(person1.getName()); // John (unchanged)
System.out.println(person2.getName()); // Mike

// Deep copy: person1 and person2 have separate objects for the age field
System.out.println(person1.getAge()); // 30
System.out.println(person2.getAge()); // 30
person2.setAge(40);
System.out.println(person1.getAge()); // 30 (unchanged)
System.out.println(person2.getAge()); // 40


In this example, we create a Person class that implements the Cloneable interface and overrides the clone() method to provide a shallow copy of the object. We create two Person objects, person1 and person2, and use the clone() method to create a new object person2 that is a clone of person1


We then demonstrate the difference between a shallow and deep copy by changing the value of the name and age fields in person2 and observing the effect on person1.