Skip to lesson

clone() and Cloneable

clone() is a method of Object that makes a new object of the same class and copies every field into it. A class can use it only when it implements the Cloneable interface and overrides clone() as public.

What Object.clone() does

clone() is a method of Object that creates a new object of the same class and copies every field into it with =, without running any constructor. It is protected, so a class must override it before other classes can call it.

Copying a student with diya.clone() sounds easy: every class inherits clone() from Object (opens in a new tab). Yet this program does not compile.

Example 1 · Mistake: calling clone() that is still protected

ProtectedCloneDemo.javaJava
class Student {    String name;    int roll;
    Student(String name, int roll) {        this.name = name;        this.roll = roll;    }}
public class ProtectedCloneDemo {    public static void main(String[] args) {        Student diya = new Student("Diya", 7);        Object copy = diya.clone();        System.out.println(copy);    }}
Sample compiler output
ProtectedCloneDemo.java:14: error: clone() has protected access in Object
        Object copy = diya.clone();
                          ^
1 error

What this code does

  • Student inherits clone() from Object, but there it is protected: only Student itself (and its children) may call it.
  • main lives in another class, so javac refuses the call. The fix is to override clone() in Student as public.

A class that wants copies overrides clone() as public. The copy it makes is like a photocopy: a new object of exactly the same class, every field copied as it is, and no constructor runs.

Cloneable, a marker interface

Cloneable is a marker interface: an interface with no methods that only tags a class as allowed to be cloned. Object.clone() checks for this tag and refuses to copy an object whose class does not have it.

This Student overrides clone() as public, so it compiles. The first call still stops the program, because one tag is missing from the class header.

What Object.clone() does. It first checks whether the class implements Cloneable. If yes, it makes a new object of the same class, copies each field with =, and runs no constructor. If no, it throws CloneNotSupportedException at run time.

Example 2 · Mistake: forgetting implements Cloneable

MissingCloneableDemo.javaJava
class Student {    String name;    int roll;
    Student(String name, int roll) {        this.name = name;        this.roll = roll;    }
    @Override    public Student clone() throws CloneNotSupportedException {        return (Student) super.clone();    }}
public class MissingCloneableDemo {    public static void main(String[] args) throws CloneNotSupportedException {        Student diya = new Student("Diya", 7);        Student copy = diya.clone();        System.out.println(copy.name);    }}
Sample output
Exception in thread "main" java.lang.CloneNotSupportedException: Student
	at java.base/java.lang.Object.clone(Native Method)
	at Student.clone(MissingCloneableDemo.java:12)
	at MissingCloneableDemo.main(MissingCloneableDemo.java:19)

What this code does

  • The code compiles, but at run time Object.clone() sees that Student is not tagged Cloneable and throws. The message names the class.
  • Read the trace from the top: it failed inside Object.clone, called from Student.clone (line 12), called from main (line 19). The fix is class Student implements Cloneable.

Unlike the interfaces (opens in a new tab) you wrote, Cloneable asks for no methods; it only gives permission. It does not even declare clone(), which is why you still override it yourself.

Overriding clone() step by step

CloneNotSupportedException is a checked exception that Object.clone() throws when the object's class does not implement Cloneable. Because it is checked, a clone() override must catch it or declare it with throws.

A working clone() has four parts: implements Cloneable, a public override, super.clone() with a cast, and a try/catch for the checked exception.

Example 3 · A working clone()

CloneDemo.javaJava
class Student implements Cloneable {    String name;    int roll;
    Student(String name, int roll) {        this.name = name;        this.roll = roll;        System.out.println("Constructor ran for " + name);    }
    @Override    public Student clone() {        try {            return (Student) super.clone();        } catch (CloneNotSupportedException e) {            throw new RuntimeException(e);        }    }}
public class CloneDemo {    public static void main(String[] args) {        Student diya = new Student("Diya", 7);        Student copy = diya.clone();
        copy.roll = 70;
        System.out.println(diya.name + " " + diya.roll);        System.out.println(copy.name + " " + copy.roll);        System.out.println("same object? " + (diya == copy));    }}
Output
Constructor ran for Diya
Diya 7
Diya 70
same object? false

What this code does

  • "Constructor ran" prints only once: super.clone() built the copy and copied its fields without calling any constructor.
  • Because the override returns Student, diya.clone() needs no cast at the call site. The copy is a separate object.

The override returns Student, not Object: a covariant return type (opens in a new tab), so callers need no cast. The cast inside is safe, because super.clone() returns an object of the real class.

The catch turns the exception into a RuntimeException; it cannot happen once the class is Cloneable. Declaring throws CloneNotSupportedException instead, as in throw and throws (opens in a new tab), forces every caller to handle it.

clone() is shallow by default

The school starts the term 2 report card as a clone of term 1. super.clone() copies each field with =, so the marks array is shared: a shallow copy (opens in a new tab).

Example 4 · Mistake: the clone shares the marks array

ShallowCloneDemo.javaJava
import java.util.Arrays;
class ReportCard implements Cloneable {    String name;    int[] marks;
    ReportCard(String name, int[] marks) {        this.name = name;        this.marks = marks;    }
    @Override    public ReportCard clone() {        try {            return (ReportCard) super.clone();        } catch (CloneNotSupportedException e) {            throw new RuntimeException(e);        }    }
    @Override    public String toString() {        return name + " " + Arrays.toString(marks);    }}
public class ShallowCloneDemo {    public static void main(String[] args) {        ReportCard term1 = new ReportCard("Kavya", new int[] {78, 64, 91});        ReportCard term2 = term1.clone();
        term2.marks[1] = 85;
        System.out.println("Term 1: " + term1);        System.out.println("Term 2: " + term2);        System.out.println("Same array? " + (term1.marks == term2.marks));    }}
Output
Term 1: Kavya [78, 85, 91]
Term 2: Kavya [78, 85, 91]
Same array? true

What this code does

  • The school starts the term 2 report card as a clone of term 1. Entering a new term 2 mark rewrote the term 1 mark too.
  • super.clone() copied the marks reference, not the array. A default clone() is a shallow copy.

Example 5 · Deep clone: fix the copy before returning it

DeepCloneDemo.javaJava
import java.util.Arrays;
class Address implements Cloneable {    String city;
    Address(String city) {        this.city = city;    }
    @Override    public Address clone() {        try {            return (Address) super.clone();        } catch (CloneNotSupportedException e) {            throw new RuntimeException(e);        }    }}
class Student implements Cloneable {    String name;    Address address;    int[] marks;
    Student(String name, Address address, int[] marks) {        this.name = name;        this.address = address;        this.marks = marks;    }
    @Override    public Student clone() {        try {            Student copy = (Student) super.clone();            copy.address = address.clone();            copy.marks = marks.clone();            return copy;        } catch (CloneNotSupportedException e) {            throw new RuntimeException(e);        }    }
    @Override    public String toString() {        return name + ", " + address.city + ", " + Arrays.toString(marks);    }}
public class DeepCloneDemo {    public static void main(String[] args) {        Student arjun = new Student("Arjun", new Address("Kochi"), new int[] {70, 82});        Student copy = arjun.clone();
        copy.address.city = "Madurai";        copy.marks[0] = 95;
        System.out.println(arjun);        System.out.println(copy);    }}
Output
Arjun, Kochi, [70, 82]
Arjun, Madurai, [95, 82]

What this code does

  • After super.clone(), the method replaces the two mutable fields on the copy: the Address with its own clone, and the array with marks.clone().
  • name is a String, so sharing it is safe. Now no change to the copy can reach Arjun's original record.

To make a clone deep, fix the copy before returning it: replace each changeable field with its own copy. Arrays make this easy: marks.clone() is public, needs no cast and throws no checked exception. For an array of objects it is still shallow.

Predict the output

What did the clone change?

Read the code and pick what it prints.

Round 1 of 2

Locker uses the default clone(). What does the program print?

class Locker implements Cloneable {
int coins;
String[] items;
Locker(int coins, String[] items) {
this.coins = coins;
this.items = items;
}
@Override
public Locker clone() {
try {
return (Locker) super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
}
public class Main {
public static void main(String[] args) {
Locker mine = new Locker(50, new String[] {"Calculator", "Lab coat"});
Locker copy = mine.clone();
copy.coins = 0;
copy.items[0] = "Pen drive";
System.out.println(mine.coins + " " + mine.items[0]);
}
}

clone() or a copy constructor?

A new ReportCard class has final fields and a constructor that checks its marks. A final field can be set only in a constructor (final variables (opens in a new tab)), and clone() runs none.

Example 6 · The same copy with a copy constructor

CopyConstructorWinsDemo.javaJava
import java.util.Arrays;
class ReportCard {    private final String name;    private final int[] marks;
    ReportCard(String name, int[] marks) {        if (marks.length == 0) {            throw new IllegalArgumentException("A report card needs marks");        }        this.name = name;        this.marks = marks.clone();    }
    ReportCard(ReportCard other) {        this(other.name, other.marks);    }
    void setMark(int subject, int mark) {        marks[subject] = mark;    }
    @Override    public String toString() {        return name + " " + Arrays.toString(marks);    }}
public class CopyConstructorWinsDemo {    public static void main(String[] args) {        ReportCard term1 = new ReportCard("Kavya", new int[] {78, 64, 91});        ReportCard term2 = new ReportCard(term1);
        term2.setMark(1, 85);
        System.out.println("Term 1: " + term1);        System.out.println("Term 2: " + term2);    }}
Output
Term 1: Kavya [78, 64, 91]
Term 2: Kavya [78, 85, 91]

What this code does

  • No Cloneable, no cast, no exception: the copy constructor sets the final fields, and the main constructor's check and array copy run for the copy too.
  • final stops the field from pointing to another array; it does not freeze the array, so setMark can still change its contents.
  • For clone(): it copies every field for you, and the copy always has the same class as the original.
  • Against clone(): it needs Cloneable, a cast and a checked exception; it skips constructors and their checks; it is shallow by default and cannot give a final field a new copy.
  • Copy constructor: plain Java, works with final fields and runs the checks, but you list the fields yourself.

Many Java developers prefer copy constructors or copyOf for new classes. You will still meet clone() in older code and in interviews, and you will use array.clone() all the time.

Fix the error

Fix the clone() errors

Read the error, then pick the line that fixes it.

Round 1 of 4

Student is Cloneable, but its clone() does not compile.

class Student implements Cloneable {
String name;
@Override
public Student clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
}

Error

Student.java:7: error: incompatible types: Object cannot be converted to Student
            return super.clone();
                              ^

Next step

Check your understanding

12 quick questions