Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Deep and Shallow Object Cloning in Java Using the Cloneable Interface

Tech 1

The Cloneable interface in Java serves as a marker indicating that objects of a class permit field-for-field duplication. When a class implements this interface, it signals to the Object.clone() method that creating bitwise copies of instances is legal permissible.

To implement basic object duplication:

class Employee implements Cloneable {
    private int employeeId;
    private String fullName;
    
    public Employee(int id, String name) {
        this.employeeId = id;
        this.fullName = name;
    }
    
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
    
    @Override
    public String toString() {
        return String.format("Employee[id=%d, name=%s]", employeeId, fullName);
    }
}

Invoking the clone operation:

public class CloningDemo {
    public static void main(String[] args) throws CloneNotSupportedException {
        Employee original = new Employee(101, "Alice Chen");
        Employee duplicate = (Employee) original.clone();
        
        System.out.println(original);
        System.out.println(duplicate);
    }
}

Key implementation requirements include overriding the clone() method with protected access, handling CloneNotSupportedException, and performing explicit casting since Object.clone() returns Object.

However, this approach creates shallow copies. When classes contain reference types, both original and cloned instances share the same nested objects:

class Department {
    public int budget;
}

class Employee implements Cloneable {
    private int employeeId;
    private String fullName;
    public Department dept = new Department();
    
    public Employee(int id, String name) {
        this.employeeId = id;
        this.fullName = name;
    }
    
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

Testing reveals the shared reference problem:

Employee original = new Employee(101, "Alice Chen");
Employee duplicate = (Employee) original.clone();

original.dept.budget = 50000;
System.out.println(duplicate.dept.budget); // Outputs 50000, demonstrating shared state

To achieve true independence through deep copying, all mutable reference types must also implement cloning:

class Department implements Cloneable {
    public int budget;
    
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

class Employee implements Cloneable {
    private int employeeId;
    private String fullName;
    public Department dept = new Department();
    
    public Employee(int id, String name) {
        this.employeeId = id;
        this.fullName = name;
    }
    
    @Override
    protected Object clone() throws CloneNotSupportedException {
        Employee cloned = (Employee) super.clone();
        cloned.dept = (Department) this.dept.clone();
        return cloned;
    }
}

This implementation ensures nested objects are duplicated rather then shared, maintaining complete separation between original and cloned instances. When original.dept.budget is modified after cloning, duplicate.dept.budget retains its initial value, confirming the deep copy behavior.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.