Skip to main content

Cloning in java with example

Understanding Object Cloning in Java

Java Object Cloning Workflow Java Object Cloning Workflow 1 Evaluate Requirements Determine if an independent duplicate object in memory is needed. 2 Implement Cloneable Add the marker interface to signal permission for duplication. 3 Invoke super.clone() Trigger the JVM native method to allocate distinct memory space. 4 Perform Shallow Copy Copy primitive values and reference pointers to the new block. 5 Handle Deep Cloning Explicitly duplicate referenced objects to avoid shared state bugs.
Figure: Java Object Cloning Workflow

Object cloning in Java refers to the process of creating an exact, independent duplicate of an existing object in memory. By default, assigning an object reference to a new variable only copies the reference address, leaving both variables pointing to the exact same memory allocation on the heap. Modifying the state via one reference directly impacts the other because they share the same underlying instance. True cloning bypasses this shared reference trap by allocating a distinct block of memory and copying the object's field values into the new space.

Pick a language, then press Listen.

Memory management and object mutability dictate when you need a cloned instance. When handling complex domain models, caching mechanisms, or undo-redo operations, passing raw references introduces unintended side effects. If a method modifies an incoming object parameter, the calling code unexpectedly breaks unless an isolated copy was passed. Implementing a robust duplication strategy ensures state encapsulation across enterprise applications.

Java provides built-in mechanisms for object copying, primarily anchored around the java.lang.Cloneable marker interface and the protected clone() method inherited from java.lang.Object. Modern enterprise systems also leverage alternative copy strategies, such as copy constructors, factory methods, or serialization, to circumvent architectural constraints inherent to the standard API.

The Mechanics of Cloneable and Marker Interfaces

The java.lang.Cloneable interface serves as a classic example of a marker interface (or tagging interface). A marker interface contains zero methods. Its sole purpose is to communicate metadata to the JVM and the compiler. When a class implements Cloneable, it signals that it permits the default field-by-field copying mechanism performed by the native super.clone() method.

If you attempt to invoke clone() on an object whose class does not implement Cloneable, the JVM throws a runtime CloneNotSupportedException. This safety check prevents accidental copying of objects that manage exclusive resources, such as open database connections, file handles, or active network sockets, which cannot be safely duplicated without explicit resource initialization.

The native clone() method performs a shallow copy. For primitive fields (like int, double, or boolean), it copies the exact value. For object reference fields, it copies the memory address (reference pointer) rather than duplicating the referenced object itself. This distinction separates shallow cloning from deep cloning.

Feature Shallow Cloning Deep Cloning
Primitive Fields Copied by value (independent) Copied by value (independent)
Object References Copied by reference (shared pointer) New instances created and recursively copied
Memory Impact Low overhead, fast execution Higher overhead, recursive allocation
Side Effects Mutating nested objects affects original and clone Mutating nested objects is completely isolated
Implementation Complexity Trivial (super.clone()) Requires manual wiring or serialization

Step-by-Step Implementation: Shallow Cloning

The following example demonstrates a standard shallow copy implementation using the Cloneable interface and the native clone() method.

package com.javatbrains.cloning;

class Employee implements Cloneable {
    int id;
    String name;

    Employee(int id, String name) {
        this.id = id;
        this.name = name;
    }

    void display() {
        System.out.println("Id = " + id);
        System.out.println("Name = " + name);
    }

    @Override
    public Employee clone() throws CloneNotSupportedException {
        System.out.println("Executing shallow clone method");
        return (Employee) super.clone();
    }
}

public class CloneDemo {
    public static void main(String[] args) throws CloneNotSupportedException {
        Employee emp = new Employee(10, "JavaTBrains");
        emp.display();

        // Create an exact shallow copy
        Employee emp1 = emp.clone();
        emp1.display();
    }
}

When executed, the program outputs:

Id = 10
Name = JavaTBrains
Executing shallow clone method
Id = 10
Name = JavaTBrains

While this works cleanly for classes consisting exclusively of primitives and immutable objects like String, it introduces critical bugs when the class contains mutable reference objects. Because String is immutable, modifying emp1.name creates a new string instance in the String pool and assigns it to emp1, leaving emp untouched. However, if Employee contained a mutable reference type like java.util.Date or a custom Address object, modifying the inner fields via the cloned object would alter the original object's state.

Implementing Deep Cloning

To ensure total isolation between the original object and its clone, you must implement deep cloning. Deep cloning requires that every mutable object reference inside the parent object is also cloned recursively.

Consider an Employee class that holds a reference to a mutable Address object. If we perform a shallow copy, both the original and the clone point to the exact same Address instance in memory.

package com.javatbrains.cloning;

class Address implements Cloneable {
    String city;

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

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

class DeepEmployee implements Cloneable {
    int id;
    String name;
    Address address;

    DeepEmployee(int id, String name, Address address) {
        this.id = id;
        this.name = name;
        this.address = address;
    }

    @Override
    public DeepEmployee clone() throws CloneNotSupportedException {
        // Perform standard shallow copy for primitives and immutable fields
        DeepEmployee cloned = (DeepEmployee) super.clone();
        
        // Explicitly deep-copy the mutable Address reference
        cloned.address = this.address.clone();
        
        return cloned;
    }
}

public class DeepCloneDemo {
    public static void main(String[] args) throws CloneNotSupportedException {
        Address address = new Address("New York");
        DeepEmployee empOriginal = new DeepEmployee(100, "Enterprise", address);
        
        DeepEmployee empClone = empOriginal.clone();
        
        // Mutate the address on the cloned object
        empClone.address.city = "Boston";
        
        System.out.println("Original City: " + empOriginal.address.city); // Prints New York
        System.out.println("Cloned City: " + empClone.address.city);     // Prints Boston
    }
}

By manually cloning the nested Address object inside the DeepEmployee.clone() method, we guarantee memory isolation. Changes made to the clone do not propagate back to the original source.

For modern domain modeling alternatives that handle immutability natively without boilerplate clone code, review Java 17 Records and Pattern Matching with Examples.

Alternative Copy Strategies: Copy Constructors and Factories

The native clone() method in Java is widely criticized in software engineering literature due to several structural flaws: it forces checked exceptions into signatures, requires casting, bypasses standard constructor execution, and mandates implementing the Cloneable interface. Because of these design drawbacks, many enterprise codebases abandon Object.clone() entirely in favor of copy constructors or static factory methods.

A copy constructor accepts an instance of the same class and copies its field values directly into the newly allocated object:

class SafeEmployee {
    private int id;
    private String name;
    private Address address;

    // Standard constructor
    public SafeEmployee(int id, String name, Address address) {
        this.id = id;
        this.name = name;
        this.address = address; // Note: In production, deep-copy this address too
    }

    // Copy Constructor
    public SafeEmployee(SafeEmployee other) {
        this.id = other.id;
        this.name = other.name;
        // Deep copy the mutable address via its own copy constructor or clone method
        this.address = new Address(other.address.city);
    }
}

Copy constructors provide compile-time safety, allow final fields to be assigned cleanly, throw no checked exceptions, and execute standard initialization logic without relying on JVM memory magic.

Real-World Edge Cases and Troubleshooting

When implementing cloning in production applications, developers frequently encounter subtle edge cases that lead to memory leaks, silent data corruption, or runtime exceptions.

1. Handling Circular References

If Object A references Object B, and Object B references Object A, a naive recursive deep-clone implementation results in an infinite loop and triggers a StackOverflowError. To resolve circular references during deep copying, maintain a mapping registry (such as an IdentityHashMap<Object, Object>) that tracks already-visited objects during the cloning traversal graph.

2. Cloning Class Hierarchies with Subclasses

If a superclass implements clone() by explicitly instantiating a new object via the new keyword (e.g., return new Employee(...)), any subclass extending that superclass will break when its clone method is invoked because it will return an instance of the parent class rather than the derived subclass type. Always rely on super.clone(), which dynamically allocates memory for the actual runtime type of the object being copied.

3. Managing Transient and Final Fields

When using serialization-based deep cloning (writing an object to an ObjectOutputStream and reading it back), any fields marked as transient are skipped and assigned their default null or zero values. If your business logic relies on transient fields (such as runtime caches or database connections), they will be lost after cloning unless explicitly re-initialized post-clone.

For containerized applications deploying cloned session states or managing runtime database resources, proper configuration is essential. Review Dockerizing a Spring Boot Application with MySQL and JNDI configuration for Tomcat 9 with Oracle for production deployment patterns.

Summary

  • Object Cloning creates an exact physical copy of an object in heap memory, moving beyond simple reference assignment.
  • Marker Interfaces like Cloneable contain no methods; they inform the JVM that a class permits the native clone() operation.
  • Shallow Cloning copies primitive values and reference addresses, leaving nested mutable objects shared between instances.
  • Deep Cloning recursively duplicates all nested mutable objects, achieving complete memory isolation between the original and the clone.
  • Copy Constructors provide a robust, type-safe alternative to Object.clone() by avoiding checked exceptions and constructor bypass issues.

Comments

Popular posts from this blog

JVM, JRE and JDK in Java

Understanding JVM, JRE, and JDK in Java Every Java developer encounters three fundamental acronyms on their first day: JVM , JRE , and JDK . Misunderstanding these foundational components leads to runtime exceptions, deployment failures, and incorrect build environments. This guide breaks down the precise architectural boundaries, memory structures, and deployment requirements of each component. ▶ Listen English (India) English (US) Hindi Telugu Tamil Kannada Malayalam Bengali Marathi Gujarati Punjabi Urdu Arabic Spanish French German Portuguese Japanese Korean Chinese (Simplified) Pick a language, then press Listen. The core problem this guide solves is ambiguous environment configuration. Developers often attempt to run production applications using a Development Kit when a Runtime Environment suffices, or they deploy platform-incompatible binaries to minimal Li...

Prime, Fibonacci and Factorial number with example in java

Mastering Prime, Fibonacci, and Factorial Algorithms in Java Prime Number Validation Workflow Prime Number Validation Workflow 1 Boundary Check Verify if the input number is less than or equal to 1. 2 Even Number Check Check if divisible by 2 and return true only if number is 2. 3 Square Root Limit Calculate integer square root as the upper loop bound. 4 Odd Factor Loop Iterate through odd integers up to limit checking divisibility. Figure: Prime Number Validation Workflow Technical coding interviews frequently test foundational algorithmic competence through three classic mathematical problems: identifying prime numbers, generating Fibonacci sequences, and calculating factorials. While these concepts originate in basic arithmetic, writing production-grade Java code to solve them requires careful attention to time complexity, memory allocation, boundary conditions, and overflow behavior. This tutorial provides rigorous, optimized Java i...

How to insert images into database using JDBC?

How to Insert Images into a Database Using JDBC Storing binary data such as images, PDFs, and application assets is a frequent requirement in enterprise software engineering. While relational databases like MySQL are optimized for structured tabular text and numeric data, they also provide robust binary storage types—specifically BLOB (Binary Large Object) variants—to handle arbitrary byte streams. When interacting with relational stores through Java, the Java Database Connectivity (JDBC) API serves as the primary bridge. ▶ Listen English (India) English (US) Hindi Telugu Tamil Kannada Malayalam Bengali Marathi Gujarati Punjabi Urdu Arabic Spanish French German Portuguese Japanese Korean Chinese (Simplified) Pick a language, then press Listen. This technical guide demonstrates how to persist image files from a local file system directly into a MySQL database usin...