Skip to content
Tutorials Center
My learning

Topics

Lesson 65 of 201 ยท Object-Oriented Programming

Copying Objects: Cloning and Copy Constructors

Learn how to copy objects in Java - reference copies, shallow vs deep copies, Cloneable and clone() pitfalls, copying arrays, and why copy constructors are preferred.

Sooner or later you'll need a copy of an object: a snapshot of a shopping cart before applying a discount, a game board to try a move on without changing the real one, or a private copy of a list a caller handed you so they can't change it behind your back. In Java, copying is less obvious than it looks, because variables hold references, and writing b = a copies the reference, not the object.

This lesson explains the three levels of "copy" (reference, shallow and deep), how Java's built-in Cloneable and clone() mechanism works and why experienced developers avoid it, how to copy arrays correctly (including 2D arrays), and the techniques modern code uses instead: copy constructors, static copy factories and immutable objects that never need copying at all.

Assignment copies the reference

As you saw in Classes and Objects, an object variable stores a reference to an object on the heap. Assigning one variable to another makes both refer to the same object:

Java Two variables, one object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

There is only one cart, so the croissant shows up in both. The same happens when you pass an object to a method or return one from a getter: the reference travels, the object stays put (Parameters and Return Values). To get an independent object, you must create a new one and fill it with the old one's data.

Shallow copy versus deep copy

Once you create a new object, the question is what to do with fields that are themselves references:

  • A shallow copy creates a new outer object, but copies each field's value as-is. Primitive fields are duplicated; reference fields still point to the same inner objects.
  • A deep copy also copies the mutable objects the fields refer to (and their mutable fields, and so on), so the copy shares nothing changeable with the original.
Java Shallow and deep copies of the same object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Both copies kept the old name, because rename replaced the original's name field and didn't touch the copies' fields. But the shallow copy also gained Chloe, because it shares the list object with the original. The deep copy has its own list.

The names inside the list are Strings, which are immutable, so sharing them is perfectly safe. That's the practical rule for deep copies: copy every mutable object, share every immutable one. If the list held mutable Player objects, a truly deep copy would copy each player too.

Cloneable and clone()

Java has a built-in copying mechanism inherited from Object:

  • Object.clone() is a protected method that creates a new object of the same runtime class and copies every field (a shallow copy), without calling any constructor.
  • It only works if the class implements the marker interface Cloneable (Interfaces). Otherwise it throws the checked exception CloneNotSupportedException.

To make a class cloneable you implement Cloneable, override clone() as public with a covariant return type, call super.clone(), and then fix up any mutable fields to make the copy deep enough:

Java Overriding clone() correctly, and what happens without Cloneable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

This works, but look at what it took:

  • cells and notes can't be final, because clone() has to reassign them after super.clone(). A final field can only be assigned in a constructor, and clone() isn't one. That fights directly against immutability.
  • super.clone() throws a checked exception that can never happen here, so every override wraps it in a try/catch.
  • No constructor runs. Any validation, counters or registration in the constructor are skipped for clones.
  • Cloneable has no methods. It changes the behavior of a protected method in another class, which is an unusual and confusing design, and Cloneable as a type doesn't even let you call clone().
  • Every class in the hierarchy must cooperate. If a superclass's clone() forgets to deep-copy its own mutable fields, your subclass can't fix it, because it can't reach those private fields.
  • Forgetting the fix-up step for a single field gives a shallow copy that silently shares state, like the shallow Team above.

For these reasons, the common advice is: don't implement Cloneable in new classes. You need to understand clone() because you'll meet it in older code and in the JDK (for example ArrayList.clone() and HashMap.clone(), which are both shallow), and because arrays rely on it.

Copying arrays

Arrays are the one place where clone() is simple and recommended. Every array has a public clone() that returns the right type with no casts or exceptions. Arrays.copyOf and System.arraycopy do the same job with more control (Looping Through Arrays).

But an array clone is still shallow. For a 2D array, which is an array of row arrays, cloning copies the outer array and shares the rows:

Java clone() on 1D and 2D arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Changing shallow[0][0] changed board, because both outer arrays point to the same first row. Copy each row to get an independent grid. The one-line stream version does the same thing for any 2D array. For arrays of mutable objects, you also need to copy each element.

Copy constructors and copy factories

The preferred way to copy is to write it yourself, as ordinary code:

  • A copy constructor takes an object of the same class and initializes the new object from it: new Recipe(other).
  • A static copy factory does the same with a descriptive name: Recipe.copyOf(other).

Because they are normal constructors and methods, they can use final fields, run validation, throw no checked exceptions, and decide field by field what to copy deeply. The JDK uses this style everywhere: new ArrayList<>(collection), new HashMap<>(map), List.copyOf(collection), new StringBuilder(charSequence).

Java A copy constructor and a copy factory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The copy constructor reuses the main constructor through this(...), so the servings check runs for copies too, and ingredients stays final. Each Ingredient is copied because it's mutable; changing the party recipe's flour leaves the original at 200 g.

One limitation: a copy constructor creates exactly the class it belongs to. If a variable of type Shape might hold a Circle or a Square, new Shape(shape) can't produce the right subclass. In that case, declare an instance method such as Shape copy() that each subclass overrides to call its own copy constructor. That is the prototype pattern done safely (Creational Design Patterns).

Defensive copies

A copy you make to protect your object's state is called a defensive copy. Make one in two places:

  • When you receive a mutable object to store (in a constructor or setter), so the caller can't change it later.
  • When you return internal mutable state from a getter, so the receiver can't change it.
Java
final class Schedule {
    private final List<LocalDate> dates;

    Schedule(List<LocalDate> dates) {
        this.dates = List.copyOf(dates);   // copy in (also unmodifiable)
    }

    List<LocalDate> dates() {
        return dates;                      // already unmodifiable: safe to return
    }
}

List.copyOf gives an unmodifiable copy, and since LocalDate is immutable, no element copying is needed. If the copy is unmodifiable, the getter can return it directly. Encapsulation, Getters and Setters covers this habit in context.

The best copy is no copy

Immutable objects can be shared freely: nobody can change them, so there's nothing to protect. String, Integer, LocalDate, BigDecimal, List.of(...) and well-designed records never need copying. To "change" one, you create a new object with the new values, for example with a record's withX(...) method.

That's why modern Java code copies far less than older code. When you design a class, ask first whether it can be immutable. If it must be mutable, give it a copy constructor or factory, and copy only the fields that need it.

Two more techniques you may encounter: deep copying through serialization (write the object to bytes and read it back) works for any Serializable graph, but it's slow and has security risks; and libraries like Jackson can copy by converting to JSON and back. Both are last resorts.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. List<String> a = new ArrayList<>(List.of("x")); List<String> b = a; b.add("y"); What does a contain?

    b = a copies the reference, so both variables refer to the same list. Adding through b changes the only list there is.
  2. 2. What does a shallow copy of an object with a List field share with the original?

    A shallow copy creates a new outer object, but reference fields still point to the same inner objects, so changes to the list are visible through both.
  3. 3. A class doesn't implement Cloneable, and one of its methods calls super.clone(). What happens?

    Object.clone() checks for the Cloneable marker interface and throws CloneNotSupportedException if it's missing.
  4. 4. int[][] g = {{1, 2}, {3, 4}}; int[][] c = g.clone(); c[0][0] = 9; What is g[0][0] now?

    Cloning a 2D array copies only the outer array; both outer arrays share the same row arrays, so the change is visible through g. Clone each row for a deep copy.
  5. 5. Why are copy constructors usually preferred over clone()?

    A copy constructor is ordinary code, so it can assign final fields, reuse constructor checks and copy exactly what needs copying. It doesn't deep-copy automatically; you decide.

Summary

  • Assigning, passing or returning an object copies the reference; both variables then share one object.
  • A shallow copy duplicates the outer object but shares the objects its fields refer to; a deep copy also copies mutable inner objects. Immutable parts can be shared safely.
  • Object.clone() makes a shallow field-by-field copy without calling a constructor, only for classes that implement Cloneable; overriding it well requires non-final fields and a try/catch. Avoid it in new classes.
  • Array clone() is fine but shallow: copy each row of a 2D array, and each mutable element of an object array.
  • Prefer copy constructors and static copy factories, like the JDK's new ArrayList<>(list) and List.copyOf. Use an overridable copy() method when the exact subclass matters.
  • Make defensive copies when storing or returning mutable state, and prefer immutable objects, which never need copying.

Next: Sealed Classes and Interfaces, where you'll control exactly which classes may extend a type.