What is deep and shallow cloning, and how is the Cloneable interface used?

Deep and shallow cloning are techniques used to create copies of objects. In shallow cloning, the object itself is copied, but any referenced objects are shared between the original and the clone. In deep cloning, both the object and all objects it references are duplicated, creating completely independent copies. The Cloneable interface acts as a marker interface that indicates a class supports cloning through the clone() method.

Key Points

Example

Consider an Employee object that contains an Address object. In shallow cloning, both Employee objects refer to the same Address. If the address changes in one object, it changes for the other. In deep cloning, each Employee gets its own Address copy.

class Address implements Cloneable {

    String city;

    Address(String city) {
        this.city = city;
    }

    @Override
    protected Address clone()
            throws CloneNotSupportedException {

        return (Address) super.clone();
    }
}

class Employee implements Cloneable {

    String name;
    Address address;
    Employee(String name,
             Address address) {

        this.name = name;
        this.address = address;
    }

    @Override
    protected Employee clone()
            throws CloneNotSupportedException {

        Employee cloned =
                (Employee) super.clone();

        // Deep Clone
        cloned.address =
                address.clone();

        return cloned;
    }
}

public class Main {

    public static void main(String[] args)
            throws Exception {

        Employee emp1 =
                new Employee(
                        "John",
                        new Address("Pune"));

        Employee emp2 =
                emp1.clone();

        emp2.address.city = "Mumbai";

        System.out.println(
                emp1.address.city);

        System.out.println(
                emp2.address.city);
    }
}

Interview Tip

A concise interview answer is: Shallow cloning copies an object while sharing references to nested objects, whereas deep cloning creates independent copies of both the object and its referenced objects. The Cloneable interface marks a class as cloneable, and the clone() method must be overridden to define whether cloning should be shallow or deep.

Last updated: 11 November 2026

Previous question: How can a singleton class be broken, and how do you make sure only one object is created?

Next question: Why do people regard Java 8 lambda expressions as a big change in the Java programming language?

More Core Java - Level IV (Advanced) interview questions

All Core Java - Level IV (Advanced) questions