0
0
JavaHow-ToBeginner · 4 min read

How to Clone Object in Java: Syntax and Examples

In Java, you can clone an object by implementing the Cloneable interface and overriding the clone() method from the Object class. Then, call super.clone() inside your clone() method to create a copy of the object.
📐

Syntax

To clone an object in Java, your class must implement the Cloneable interface and override the clone() method. Inside this method, you call super.clone() to create a shallow copy of the object.

  • Cloneable: A marker interface that allows the clone() method to work.
  • clone() method: Creates and returns a copy of the object.
  • super.clone(): Calls the Object class's clone method to perform the actual copying.
java
public class MyClass implements Cloneable {
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
💻

Example

This example shows how to clone a simple object with one field. It demonstrates creating an original object, cloning it, and printing both to verify they are separate objects.

java
class Person implements Cloneable {
    String name;

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

    @Override
    protected Person clone() throws CloneNotSupportedException {
        return (Person) super.clone();
    }

    @Override
    public String toString() {
        return "Person{name='" + name + "'}";
    }
}

public class Main {
    public static void main(String[] args) {
        try {
            Person original = new Person("Alice");
            Person copy = original.clone();

            System.out.println("Original: " + original);
            System.out.println("Copy: " + copy);

            System.out.println("Are they the same object? " + (original == copy));
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }
}
Output
Original: Person{name='Alice'} Copy: Person{name='Alice'} Are they the same object? false
⚠️

Common Pitfalls

Many beginners forget to implement the Cloneable interface, which causes clone() to throw CloneNotSupportedException. Also, the default clone() method performs a shallow copy, so if your object has fields that are objects themselves, those fields are not deeply cloned.

To fix this, you can override clone() to clone mutable fields manually for a deep copy.

java
class Address {
    String city;

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

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 the Address object
        cloned.address = new Address(this.address.city);
        return cloned;
    }
}

// Without deep clone, both objects share the same Address instance, causing bugs.
📊

Quick Reference

  • Implement Cloneable to allow cloning.
  • Override clone() and call super.clone().
  • Handle CloneNotSupportedException with try-catch or throws.
  • Use deep cloning for objects with mutable fields.

Key Takeaways

Implement the Cloneable interface to enable object cloning in Java.
Override the clone() method and call super.clone() to create a copy.
Default cloning is shallow; manually clone mutable fields for deep copies.
Always handle CloneNotSupportedException when calling clone().
Cloning creates a new object with the same field values but different reference.