Menu
Coddy logo textTech

clone() Method

Part of the Object Oriented Programming section of Coddy's Java journey — lesson 43 of 87.

The clone() method creates a copy of an object. To use it, your class must implement the Cloneable interface and override the clone() method from the Object class.

public class Person implements Cloneable {
    private String name;
    private int age;
    
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    @Override
    public Person clone() {
        try {
            return (Person) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new RuntimeException(e);
        }
    }
}

Now you can create independent copies of objects:

Person original = new Person("Alice", 25);
Person copy = original.clone();
// copy is a separate object with the same values

By default, clone() performs a shallow copy, meaning it copies primitive values and references. If your object contains other objects as fields, both the original and clone will reference the same nested objects. For truly independent copies with nested objects, you need to implement a deep copy by also cloning those nested objects within your clone() method.

challenge icon

Challenge

Easy

Let's build a document management system that demonstrates object cloning. You'll create a Document class that can be cloned to create independent copies, allowing users to duplicate documents while keeping the original intact.

You'll organize your code across two files:

  • Document.java: Create a class representing a document that supports cloning. A Document has three private fields: title (String), author (String), and version (int). Include a constructor to initialize all fields and getter methods for each. Also add a setVersion(int version) method to update the version number.

    Make your Document class implement the Cloneable interface and override the clone() method to return a Document. Handle the CloneNotSupportedException inside the method by wrapping it in a RuntimeException.

    Override toString() to return: Document[title=X, author=Y, version=Z] where X, Y, and Z are the actual field values.

  • Main.java: Bring your Document class to life by creating a document and cloning it. You'll receive three inputs: a title (String), an author (String), and a version number (int).

    Create an original Document with these values, then clone it to create a copy. After cloning, modify the copy's version by incrementing it by 1 using setVersion(). This demonstrates that the clone is truly independent from the original.

    Print three lines:

    1. Original: followed by the original document's toString()
    2. Clone: followed by the cloned document's toString()
    3. Independent: followed by true or false indicating whether the original and clone are different objects (use != comparison)

You will receive three inputs: the document title (String), the author name (String), and the version number (int).

Notice how after modifying the clone's version, the original document remains unchanged—this proves that clone() created a truly independent copy!

Cheat sheet

The clone() method creates a copy of an object. To use it, your class must implement the Cloneable interface and override the clone() method from the Object class:

public class Person implements Cloneable {
    private String name;
    private int age;
    
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    @Override
    public Person clone() {
        try {
            return (Person) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new RuntimeException(e);
        }
    }
}

Creating independent copies:

Person original = new Person("Alice", 25);
Person copy = original.clone();
// copy is a separate object with the same values

By default, clone() performs a shallow copy, copying primitive values and references. If your object contains other objects as fields, both the original and clone will reference the same nested objects. For truly independent copies with nested objects, implement a deep copy by also cloning those nested objects within your clone() method.

Try it yourself

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // Read inputs
        String title = scanner.nextLine();
        String author = scanner.nextLine();
        int version = scanner.nextInt();
        
        // TODO: Create an original Document with the input values
        
        // TODO: Clone the original document to create a copy
        
        // TODO: Modify the clone's version by incrementing it by 1
        
        // TODO: Print "Original: " followed by the original document
        
        // TODO: Print "Clone: " followed by the cloned document
        
        // TODO: Print "Independent: " followed by true/false (check if original != clone)
        
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming