object cloning in java

What is object cloning in java with example

Object cloning in Java is the process of creating a duplicate copy of an object. Cloning is used to create an exact copy of an object, including its state. The clone() method is used to perform object cloning in Java. It’s defined in the Object class and is protected, which means you need to override it in your class to make it accessible from outside the class.

Here’s how you can implement object cloning in Java with an example:

 * Author: Zameer Ali
 * */
// A class that implements Cloneable to enable cloning
class Person implements Cloneable {
    private String name;

    public Person(String name) {
        this.name = name;

    public String getName() {
        return name;

    // Override the clone method to enable cloning
    public Object clone() throws CloneNotSupportedException {
        return super.clone();

public class CloningExample {
    public static void main(String[] args) {
        // Creating an object of the Person class
        Person originalPerson = new Person("John");

        try {
            // Cloning the originalPerson object
            Person clonedPerson = (Person) originalPerson.clone();

            // Modifying the cloned object
            clonedPerson.getName(); // Output: John

            // Printing the values of original and cloned objects
            System.out.println("Original Person: " + originalPerson.getName()); // Output: John
            System.out.println("Cloned Person: " + clonedPerson.getName());     // Output: Alice
        } catch (CloneNotSupportedException e) {
            System.out.println("Cloning not supported: " + e.getMessage());

In this example, the Person class implements the Cloneable interface, allowing objects of this class to be cloned. The clone() method is overridden to provide a proper implementation of cloning.

Please note that clone() method returns an Object type, so you need to cast it to the appropriate type. Also, cloning can throw CloneNotSupportedException if the class doesn’t implement Cloneable.

Keep in mind that the default clone() method performs a shallow copy, meaning that it creates a new object but does not create copies of the objects referenced by the original object. If your class contains reference variables pointing to mutable objects, you might need to perform a deep copy to ensure that the cloned object is fully independent of the original one.

Leave a Reply

Your email address will not be published. Required fields are marked *