Cloning and Copy Constructors

Shallow and deep copies, seen as arrows between objects.

5 lessons · 9 past questions · 44 marks in the papers collected here

Open the interactive lessons →Cloning and Copy Constructors past questions

Diagrams, animations, quizzes and checked solutions are on the interactive pages.

Contents

  1. A second name or a second object
  2. What a shallow clone shares
  3. Cutting the shared arrows: deep cloning
  4. Who may be cloned: the contract and inheritance
  5. Copy constructors

1. A second name or a second object

Some lines add a name. Some lines add an object.

the difference between assigning a reference and cloning an object

You have a lamp object set to 40 watts. You want to try 45 watts without touching the real lamp. Writing Lamp trial = hall; looks like a copy. Then trial.watts = 45; also changes hall.watts. Why?

A variable of a class type holds a reference, an arrow to an object. A street address on a slip of paper works the same way: copying the slip gives two slips and still one house. The picture stops being true in one place: Java may reclaim an object once no reference reaches it, while a house stays.

To get a second house you must build one. hall.clone() asks Java to make a new object of the same class and to fill its fields from the original. Later writes into the new object's own fields cannot be seen through the old arrow, because they land in a different box.

How do you write it? Object already has a method called clone. To offer it to the outside world, a class does three things: it says implements Cloneable, it declares a public method clone(), and that method calls super.clone(). The call can throw the checked exception CloneNotSupportedException, hence the throws clause. The section Who may be cloned explains each of the three.

What super.clone() does

It creates a new object of the same runtime class. It then copies the fields one by one: a primitive field gets the same value, a reference field gets the same arrow. No constructor runs.

Worked example: One lamp, two names

Problem.

same is assigned from hall, and spare is cloned from hall. What do the two output lines show?

class Lamp implements Cloneable {
    int watts;
    Lamp(int watts) { this.watts = watts; }
    public Lamp clone() throws CloneNotSupportedException {
        return (Lamp) super.clone();
    }
}
public class Main {
    public static void main(String[] args) throws CloneNotSupportedException {
        Lamp hall = new Lamp(40);
        Lamp same = hall;
        Lamp spare = hall.clone();
        same.watts = 60;
        spare.watts += 5;
        System.out.println(hall.watts + " " + same.watts + " " + spare.watts);
        System.out.println((hall == same) + " " + (hall == spare));
    }
}

What is asked.

Both lines.

Idea.

Count the objects first, then apply each write to its box.

  1. new Lamp(40) makes object 1.
  2. same = hall adds a name for object 1.
  3. hall.clone() makes object 2 with watts equal to 40.
  4. same.watts = 60 writes object 1.
  5. spare.watts += 5 writes object 2: 40 becomes 45.
  6. The first line reads objects 1, 1 and 2: 60 60 45. The second line asks about identity: true false.

Answer.

60 60 45 then true false

Common mistake.

Reading same = hall as a copy.

What if

The program prints 60 60 45 and true false.

  • The third object line becomes Lamp spare = same;. What are the two lines now?
    It prints 65 65 65 and true true.. Only one object exists. Both writes land in it.
  • Lamp spare = hall.clone(); moves below same.watts = 60;. What is the first line?
    It prints 60 60 65 and true false.. The clone copies the values that exist when it is called, so spare starts at 60.
  • spare.watts += 5; becomes hall.watts += 5;. What is the first line?
    It prints 65 65 40 and true false.. The clone stays at 40 because neither write reaches it.

Second name against second object

Alias

One object after this line.

Lamp spare = hall;

Clone

Two objects after this line.

Lamp spare = hall.clone();

The difference. Only the right side calls clone().

Without new or clone() (or a method that uses one of them), an assignment adds a name only.

Worked example: Text, numbers and a third name

Problem.

second is a clone of first, and third is assigned from second. A constructor prints a line. What is the full output?

class Badge implements Cloneable {
    String owner;
    int floor;
    Badge(String owner, int floor) {
        this.owner = owner;
        this.floor = floor;
        System.out.println("built " + owner);
    }
    Badge duplicate() throws CloneNotSupportedException {
        return (Badge) super.clone();
    }
    String line() { return owner + " on " + floor; }
}
public class Main {
    public static void main(String[] args) throws CloneNotSupportedException {
        Badge first = new Badge("Anu", 2);
        Badge second = first.duplicate();
        Badge third = second;
        second.owner = "Bela";
        third.floor = 7;
        first.floor++;
        System.out.println(first.line());
        System.out.println(second.line());
        System.out.println(third.line());
    }
}

What is asked.

All printed lines.

Idea.

Draw two boxes. third is a second arrow to the second box.

  1. new Badge("Anu", 2) runs the constructor and prints built Anu.
  2. duplicate() is a method of the class that returns super.clone(); its name is free. The call first.duplicate() copies both fields. The constructor does not run, so no second built line appears.
  3. third = second adds a name for box 2.
  4. second.owner = "Bela" assigns a field of box 2. Box 1 still refers to the text Anu.
  5. third.floor = 7 writes box 2. first.floor++ makes box 1 hold 3.
  6. Output: built Anu, Anu on 3, Bela on 7, Bela on 7.

Answer.

built Anu, Anu on 3, Bela on 7, Bela on 7

Common mistake.

Printing built twice, or letting Bela appear in the first object.

Notice that

second.owner = "Bela" did not change a text. It moved one arrow to another text. A String object can never change its letters; such an object is called immutable. That is why a shared String field causes no trouble.

super.clone() copies field by field

  1. One Lamp exists. It has a number and a reference to a text.
  2. super.clone() makes a new object of the same runtime class. No constructor runs.
  3. A primitive field is copied as a value. The two objects now hold their own 40.
  4. A reference field is copied as a reference. No second String is made.
  5. The cast result is stored in spare. hall == spare is false.
  6. Changing a number in the copy leaves the original alone.
When This Breaks

"The copy is independent" holds for fields that are assigned afterwards. It breaks when a field refers to an object that can change, such as an array: copy.data[0] = 1; assigns no field of the copy, it writes inside an object that both share.

2. What a shallow clone shares

The outer box is new. What it points to is old.

what happens to arrays and other objects reached through a cloned object

A suitcase object has a weight, a name label and a list of pocket contents. You clone it to plan a second trip. You change the destination on the copy's label, and the original label changes too. The clone did make a second suitcase. So what happened?

The suitcase does not hold the label inside it. It holds an arrow to the label. Think of two index cards that both say "see shelf 4": rewriting what is on shelf 4 affects both cards. The picture stops being true if you erase one card's note and write "see shelf 9": only that card changes.

Why does Java copy this way? super.clone() knows only the fields of the object. It cannot know whether you want the label shared or separate, so it copies what is stored: the arrow. This result is called a shallow copy.

Worked example: Pack a second suitcase

Problem.

The copy changes its weight, the label's city and one pocket. What do mine and yours show?

class Label {
    String city;
    Label(String city) { this.city = city; }
}
class Suitcase implements Cloneable {
    int kilos;
    Label label;
    int[] pockets;
    Suitcase(int kilos, Label label, int[] pockets) {
        this.kilos = kilos;
        this.label = label;
        this.pockets = pockets;
    }
    public Suitcase clone() throws CloneNotSupportedException {
        return (Suitcase) super.clone();
    }
    String show() { return kilos + " " + label.city + " " + pockets[1]; }
}
public class Main {
    public static void main(String[] args) throws CloneNotSupportedException {
        Suitcase mine = new Suitcase(12, new Label("Goa"), new int[] {1, 2});
        Suitcase yours = mine.clone();
        yours.kilos = 15;
        yours.label.city = "Pune";
        yours.pockets[1] = 8;
        System.out.println(mine.show());
        System.out.println(yours.show());
    }
}

What is asked.

Both lines.

Idea.

Ask of every write: is it a field of the copy, or something reached through a field?

  1. The clone has its own kilos, label and pockets fields. The last two hold the same arrows as in mine.
  2. yours.kilos = 15 assigns a field of the copy only.
  3. yours.label.city = "Pune" follows the arrow and writes in the one shared label.
  4. yours.pockets[1] = 8 writes in the one shared array.
  5. mine shows 12, Pune, 8. yours shows 15, Pune, 8.

Answer.

12 Pune 8 then 15 Pune 8

Common mistake.

Printing Goa for the original because a clone was made.

What if

The program prints 12 Pune 8 and 15 Pune 8.

  • yours.label.city = "Pune"; becomes yours.label = new Label("Pune");. What does the first line print?
    It prints 12 Goa 8, then 15 Pune 8.. Now a field of the copy is assigned. The original arrow still ends at the old label.
  • The line mine.pockets[1] = 30; is added just before the two prints. What do both lines end with?
    It prints 12 Pune 30 and 15 Pune 30.. Sharing works in both directions: a write through the original is seen by the copy.
  • Suitcase yours = mine.clone(); becomes Suitcase yours = mine;. What does the first line print?
    Both lines print 15 Pune 8.. With an alias even the weight is shared.

Write into it, or point somewhere else

Write into the shared array

The original sees it.

copy.data[0] = 7;

Assign a new array to the field

The original does not see it.

copy.data = new int[] {7};

The difference. The left line has an index after the field; the right line assigns the field itself.

A dot or an index after the field name writes into a shared object. An = directly on the field moves one arrow.

Worked example: Share, then separate

Problem.

The copy first writes into both fields' objects, then assigns both fields, then writes again. What are the two lines?

class Kit implements Cloneable {
    int[] marks = {4, 4};
    StringBuilder colour = new StringBuilder("red");
    public Kit clone() throws CloneNotSupportedException {
        return (Kit) super.clone();
    }
}
public class Main {
    public static void main(String[] args) throws CloneNotSupportedException {
        Kit a = new Kit();
        Kit b = a.clone();
        b.marks[0] = 9;
        b.colour.append("-blue");
        b.marks = new int[] {0, 0};
        b.marks[1] = 6;
        b.colour = new StringBuilder("green");
        System.out.println(a.marks[0] + " " + a.marks[1] + " " + a.colour);
        System.out.println(b.marks[0] + " " + b.marks[1] + " " + b.colour);
    }
}

What is asked.

Both lines.

Idea.

Go line by line and mark the moment each arrow stops being shared.

  1. After the clone, a and b share the array {4, 4} and the builder red.
  2. b.marks[0] = 9 changes the shared array to {9, 4}.
  3. b.colour.append("-blue") changes the shared builder to red-blue.
  4. b.marks = new int[] {0, 0} moves only b's arrow. The next write gives b the array {0, 6}.
  5. b.colour = new StringBuilder("green") moves the other arrow of b.
  6. a reads 9 4 red-blue; b reads 0 6 green.

Answer.

9 4 red-blue then 0 6 green

Common mistake.

Undoing the two early writes once b gets new objects. They already happened to the shared objects.

A shallow clone shares what the fields point to

  1. One suitcase points at one label and one array.
  2. The clone copies three fields. Both suitcases point at the same label and array.
  3. A number belongs to one object only. mine.kilos stays 12.
  4. yours.label.city follows the arrow and writes in the shared label. mine sees Pune.
  5. The array is shared too. mine prints 12 Pune 8 and yours prints 15 Pune 8.
When This Breaks

"The copy changed it, so the original sees it" breaks when the shared object cannot change. copy.name = copy.name.toUpperCase(); creates a new String and assigns the copy's field, so the original keeps its letters.

3. Cutting the shared arrows: deep cloning

Make new inner boxes, then point the copy at them.

how a clone method gives the copy its own inner objects

A drone has a motor object and a route array. You clone the drone to test a new motor speed. With a plain super.clone() the test would also speed up the real drone. You need a second motor and a second route.

Think of photocopying a folder that contains a list of other folders. Copying the cover and the list is not enough: you must also copy each listed folder. The picture stops being true for sheets nobody can write on. Those may stay shared, like String objects.

Why two steps? First call super.clone() to get an object of the right class with all fields filled. Then overwrite each reference field that needs its own object. Until the second step runs, the copy is still shallow.

The pattern

Type copy = (Type) super.clone(); then, for each mutable field, copy.field = field.clone(); and finally return copy;. An inner object of your own class can be cloned this way only if that class offers a clone() that this code may call.

Worked example: A drone with its own parts

Problem.

The copy renames itself, speeds up its motor and edits its route. What do the two drones show?

class Motor implements Cloneable {
    int rpm;
    Motor(int rpm) { this.rpm = rpm; }
    public Motor clone() throws CloneNotSupportedException {
        return (Motor) super.clone();
    }
}
class Drone implements Cloneable {
    String code;
    Motor motor;
    int[] route;
    Drone(String code, Motor motor, int[] route) {
        this.code = code;
        this.motor = motor;
        this.route = route;
    }
    public Drone clone() throws CloneNotSupportedException {
        Drone copy = (Drone) super.clone();
        copy.motor = motor.clone();
        copy.route = route.clone();
        return copy;
    }
    String show() { return code + " " + motor.rpm + " " + route[0]; }
}
public class Main {
    public static void main(String[] args) throws CloneNotSupportedException {
        Drone a = new Drone("A1", new Motor(900), new int[] {2, 6});
        Drone b = a.clone();
        b.code = "B2";
        b.motor.rpm = 1200;
        b.route[0] = 3;
        System.out.println(a.show());
        System.out.println(b.show());
    }
}

What is asked.

Both lines.

Idea.

Check which fields were replaced inside clone().

  1. clone() starts with a shallow copy.
  2. motor.clone() gives the copy a second Motor.
  3. route.clone() gives the copy a second array.
  4. The three later writes use b and touch only b's own objects.
  5. a keeps A1, 900, 2. b shows B2, 1200, 3.

Answer.

A1 900 2 then B2 1200 3

Common mistake.

Letting 1200 appear in a out of habit from shallow questions.

What if

The program prints A1 900 2 and B2 1200 3.

  • The line copy.route = route.clone(); is deleted. What is the first line?
    It prints A1 900 3, then B2 1200 3.. The array is shared again, so the route write is seen by a.
  • Only the line copy.motor = motor.clone(); is deleted. What is the first line?
    It prints A1 1200 2, then B2 1200 3.. One motor serves both drones.
  • The first drone is built with null as its motor. What happens when it is cloned?
    It throws NullPointerException inside clone().. motor.clone() calls a method on null. A guard such as motor == null ? null : motor.clone() avoids it.

Shallow body against deep body

Shallow

The array stays shared.

Drone copy = (Drone) super.clone();
return copy;

Deep for the route

The copy owns its array.

Drone copy = (Drone) super.clone();
copy.route = route.clone();
return copy;

The difference. One extra assignment replaces a copied arrow.

Read the body of clone() before the main method. Each inner assignment removes one piece of sharing.

Worked example: A garden bed with plants

Problem.

clone() builds a new list and puts a clone of every plant in it. The copy then removes its first plant, edits the plant now at index 0 and adds one. What prints?

import java.util.ArrayList;

class Plant implements Cloneable {
    String kind;
    int height;
    Plant(String kind, int height) {
        this.kind = kind;
        this.height = height;
    }
    public Plant clone() throws CloneNotSupportedException {
        return (Plant) super.clone();
    }
    public String toString() { return kind + "=" + height; }
}
class Bed implements Cloneable {
    ArrayList<Plant> plants = new ArrayList<>();
    public Bed clone() throws CloneNotSupportedException {
        Bed copy = (Bed) super.clone();
        copy.plants = new ArrayList<>();
        for (Plant p : plants) {
            copy.plants.add(p.clone());
        }
        return copy;
    }
}
public class Main {
    public static void main(String[] args) throws CloneNotSupportedException {
        Bed north = new Bed();
        north.plants.add(new Plant("fern", 10));
        north.plants.add(new Plant("mint", 4));
        Bed south = north.clone();
        south.plants.remove(0);
        south.plants.get(0).height = 25;
        south.plants.add(new Plant("sage", 2));
        System.out.println(north.plants);
        System.out.println(south.plants);
    }
}

What is asked.

Both lists.

Idea.

Two levels must be separate: the list and each plant.

  1. super.clone() copies the arrow to the list.
  2. A fresh list is assigned to the copy.
  3. The loop adds a clone of each plant, so four Plant objects exist.
  4. south.plants.remove(0) takes the fern out of the copy's list only.
  5. get(0) is now the copy's own mint, so its height becomes 25.
  6. add changes only the copy's list.
  7. The first list is still [fern=10, mint=4]; the second is [mint=25, sage=2].

Answer.

[fern=10, mint=4] then [mint=25, sage=2]

Common mistake.

Stopping at the new list and forgetting what the loop adds to it.

A deep clone replaces each shared arrow

  1. The original drone owns one motor and one route array.
  2. Step one is super.clone(). For a moment the copy is shallow: both arrows are shared.
  3. copy.motor = motor.clone() makes a second motor and moves only the copy's arrow.
  4. The same is done for the array. Now no mutable object is shared.
  5. Writes through b stay in the copy. a still shows 900 and 2.

Worked example: A grid that is only half copied

Problem.

seats.clone() copies a two-dimensional array. One element is changed and one row is replaced. What prints?

public class Main {
    public static void main(String[] args) {
        int[][] seats = { {1, 1}, {2, 2} };
        int[][] plan = seats.clone();
        plan[0][0] = 7;
        plan[1] = new int[] {8, 8};
        System.out.println(seats[0][0] + " " + seats[1][0]);
        System.out.println(plan[0][0] + " " + plan[1][0]);
    }
}

What is asked.

Both lines.

Idea.

A 2-D array is an array of references to row arrays.

  1. seats.clone() makes a new outer array holding the same two row arrows.
  2. plan[0][0] = 7 writes in the shared first row.
  3. plan[1] = new int[] {8, 8} assigns a slot of the new outer array only.
  4. seats reads 7 and 2; plan reads 7 and 8.

Answer.

7 2 then 7 8

Common mistake.

Calling clone() on the outer array deep.

When This Breaks

The pattern "clone, then assign the field" fails for a final field. copy.route = route.clone(); does not compile if route is declared final int[] route, because a final field cannot be assigned again.

4. Who may be cloned: the contract and inheritance

The compiler checks two things. The running program checks one.

the three conditions for a successful clone and what subclasses inherit

A shop lets staff duplicate a stamp but not a one-time token. Both classes may contain a clone method written in the same way. One call succeeds, the other fails while the program is running. What tells them apart?

Picture a door with two guards. The compiler stands at the first: may this code call clone here, and is the checked exception handled? The running program stands at the second: is this object's class labelled Cloneable? Passing the first guard says nothing about the second.

Why a label? Copying every field is not right for every object: a copied ticket or key could be wrong. So the method in Object refuses unless a class opts in. Cloneable adds no method; it is the opt-in label, called a marker interface.

The three conditions

ConditionChecked byIf missing
A clone method you are allowed to call (Object.clone is protected, so classes usually declare a public one)compilercompilation error
CloneNotSupportedException caught or declaredcompilercompilation error
The runtime class implements Cloneablerunning program, inside Object.cloneCloneNotSupportedException is thrown

Worked example: Stamp yes, token no

Problem.

Only Stamp implements Cloneable. Both are cloned inside one try. What prints?

class Stamp implements Cloneable {
    int value = 5;
    public Stamp clone() throws CloneNotSupportedException {
        return (Stamp) super.clone();
    }
}
class Token {
    int value = 2;
    public Token clone() throws CloneNotSupportedException {
        return (Token) super.clone();
    }
}
public class Main {
    public static void main(String[] args) {
        try {
            Stamp s = new Stamp().clone();
            System.out.println("stamp " + s.value);
            Token t = new Token().clone();
            System.out.println("token " + t.value);
        } catch (CloneNotSupportedException e) {
            System.out.println("refused");
        }
        System.out.println("end");
    }
}

What is asked.

All lines.

Idea.

Run the calls in order and stop the try at the first refusal.

  1. The file compiles: both clone methods are public and the exception is caught.
  2. new Stamp().clone() succeeds, so stamp 5 is printed.
  3. new Token().clone() reaches Object.clone, which finds no Cloneable label and throws.
  4. The line printing the token is skipped; the catch prints refused.
  5. The program goes on and prints end.

Answer.

stamp 5, refused, end

Common mistake.

Calling the missing implements Cloneable a compilation error.

What if

The program prints stamp 5, refused, end.

  • Token is declared implements Cloneable. What prints now?
    It prints stamp 5, token 2, end.. Both runtime classes pass the test, so the catch never runs.
  • Stamp loses implements Cloneable and Token still lacks it. How many lines print?
    It prints refused and end.. The first clone already throws, so the rest of the try is skipped.
  • The try and catch are removed and main declares nothing. Does it compile?
    No, it is a compilation error.. clone() declares a checked exception, which must be caught or declared.

The Cloneable test happens while the program runs

  1. new Stamp().clone() is about to run. The compiler already accepted every line.
  2. Inside Object.clone the runtime class is tested: does Stamp implement Cloneable? Yes.
  3. A copy is made and stamp 5 is printed.
  4. Token has a clone method but lacks implements Cloneable.
  5. CloneNotSupportedException leaves the call. The rest of the try is skipped and refused is printed.
  6. Execution continues after the catch and prints end.

Now families. A parent class declares Cloneable and a clone method. A child inherits both. When the child object is cloned, super.clone() travels up to Object, which looks at the runtime class. So the result is again a child object, with the inherited fields and the child's own fields copied.

Worked example: Cloning through the parent type

Problem.

An Organ is held in an Instrument variable and cloned. Organ declares no clone and no implements. What prints?

class Instrument implements Cloneable {
    int volume = 3;
    public Instrument clone() throws CloneNotSupportedException {
        return (Instrument) super.clone();
    }
    String sound() { return "hum"; }
}
class Organ extends Instrument {
    int pipes = 8;
    @Override
    String sound() { return "chord"; }
}
public class Main {
    public static void main(String[] args) throws CloneNotSupportedException {
        Instrument one = new Organ();
        Instrument two = one.clone();
        two.volume = 9;
        System.out.println(two.sound() + " " + two.getClass().getSimpleName());
        System.out.println(((Organ) two).pipes + " " + one.volume + " " + two.volume);
        System.out.println(two instanceof Cloneable);
    }
}

What is asked.

All three lines.

Idea.

The static type decides what you may write; the runtime class decides what is built.

  1. one.clone() runs the inherited method.
  2. Object.clone sees the runtime class Organ, which is Cloneable through its parent.
  3. The result is a new Organ: sound() returns chord and its class name is Organ.
  4. pipes was copied (8). The write two.volume = 9 leaves one.volume at 3.
  5. two instanceof Cloneable is true.

Answer.

chord Organ, 8 3 9, true

Common mistake.

Expecting an Instrument because the variable and the method are declared there.

Worked example: A child adds a field

Problem.

Shelter.clone() copies its own array. Tent adds a second array and overrides nothing. What prints?

class Shelter implements Cloneable {
    int[] poles = {2};
    public Shelter clone() throws CloneNotSupportedException {
        Shelter copy = (Shelter) super.clone();
        copy.poles = poles.clone();
        return copy;
    }
}
class Tent extends Shelter {
    int[] pegs = {6};
}
public class Main {
    public static void main(String[] args) throws CloneNotSupportedException {
        Tent a = new Tent();
        Tent b = (Tent) a.clone();
        b.poles[0] = 3;
        b.pegs[0] = 10;
        System.out.println(a.poles[0] + " " + a.pegs[0]);
        System.out.println(b.poles[0] + " " + b.pegs[0]);
    }
}

What is asked.

Both lines.

Idea.

The parent method can only copy deeply what it knows about.

  1. The clone is a Tent, and every field is first copied shallowly.
  2. The parent then replaces poles with a new array.
  3. No code replaces pegs, so it stays shared.
  4. a shows 2 and 10; b shows 3 and 10.

Answer.

2 10 then 3 10

Common mistake.

Assuming that one deep clone in the parent protects every later field.

Who handles the checked exception?

Passed to the caller

The caller must catch or declare it.

public Pen clone() throws CloneNotSupportedException {
    return (Pen) super.clone();
}

Handled inside

The caller writes no try.

public Pen clone() {
    try { return (Pen) super.clone(); }
    catch (CloneNotSupportedException e) { throw new AssertionError(); }
}

The difference. The throws clause is replaced by a try-catch inside the method.

The caller's duty comes from the throws clause of the method named by the static type.

When This Breaks

"The subclass gets a subclass copy" holds only if every class in the chain uses super.clone(). If a parent writes return new Parent(); instead, cloning a child gives a parent object, and casting it to the child throws ClassCastException.

5. Copy constructors

A constructor you write yourself that reads another object of the same class.

a constructor that builds a new object from an existing one

A music app lets you start a new playlist from an old one. You do not want to use Cloneable, a cast or a checked exception. You can write a constructor: Playlist(Playlist source).

Think of filling in a blank form by looking at a finished one. You decide for each box whether to rewrite the value or to staple a note saying "same attachment as the other form". The picture stops being true for numbers: they are always rewritten.

Why use it? It is ordinary code: no interface, no cast, no checked exception, and final fields can be filled. The price is that you must mention every field. A field that you forget keeps what a new object starts with: the value in its declaration, or else 0, false or null.

Worked example: A playlist from a playlist

Problem.

The copy appends to the mood, changes its play count and shortens a track. show() joins the mood, the second track length and the count. What do the two playlists show?

class Playlist {
    int plays;
    StringBuilder mood;
    int[] seconds;
    Playlist(String word, int first, int second) {
        mood = new StringBuilder(word);
        seconds = new int[] {first, second};
    }
    Playlist(Playlist source) {
        this.plays = source.plays;
        this.mood = source.mood;
        this.seconds = source.seconds;
    }
    String show() { return mood + " " + seconds[1] + " " + plays; }
}
public class Main {
    public static void main(String[] args) {
        Playlist base = new Playlist("calm", 200, 180);
        Playlist copy = new Playlist(base);
        copy.mood.append("-night");
        copy.plays = 4;
        copy.seconds[1] = 95;
        System.out.println(base.show());
        System.out.println(copy.show());
    }
}

What is asked.

Both lines.

Idea.

Read the copy constructor first: which assignment creates a new object?

  1. None of the three assignments creates an object, so the builder and the array are shared.
  2. copy.mood.append("-night") changes the shared builder.
  3. copy.plays = 4 assigns a number field of the new object only.
  4. copy.seconds[1] = 95 writes in the shared array.
  5. base shows calm-night, 95, 0. copy shows calm-night, 95, 4.

Answer.

calm-night 95 0 then calm-night 95 4

Common mistake.

Assuming that the word "copy" means the inner objects are copied.

What if

The program prints calm-night 95 0 and calm-night 95 4.

  • The last assignment in the copy constructor becomes this.seconds = source.seconds.clone();. What is the first line?
    It prints calm-night 180 0, then calm-night 95 4.. The new object has its own array. The builder is still shared.
  • Playlist copy = new Playlist(base); becomes Playlist copy = base;. What are both lines?
    Both print calm-night 95 4.. No constructor runs and only one object exists.
  • The line this.plays = source.plays; is deleted and base.plays = 6; is added before the copy is made, with copy.plays = 4; removed. What are the two lines?
    It prints calm-night 95 6, then calm-night 95 0.. A field that the copy constructor never assigns keeps its default.

A copy constructor does only what you wrote

  1. One playlist and one array of track lengths. The mood field is left out of this picture.
  2. new Playlist(base) creates an object with default fields, then runs your constructor with source set to base.
  3. A number is copied as a value. Each playlist now holds its own 0.
  4. This line copies the reference, not the array. This copy constructor is shallow.
  5. The new count stays in copy. A write into the array is seen by base too.

Worked example: Which class comes out?

Problem.

A WaterMeter is copied twice: once by the Meter copy constructor and once by clone(). Then the original's log changes. What prints?

import java.util.Arrays;

class Meter implements Cloneable {
    static int built = 0;
    int[] log;
    Meter(int first) {
        log = new int[] {first};
        built++;
    }
    Meter(Meter source) {
        log = Arrays.copyOf(source.log, source.log.length);
        built++;
    }
    public Meter clone() throws CloneNotSupportedException {
        return (Meter) super.clone();
    }
    String unit() { return "plain"; }
}
class WaterMeter extends Meter {
    WaterMeter() { super(30); }
    @Override
    String unit() { return "litres"; }
}
public class Main {
    public static void main(String[] args) throws CloneNotSupportedException {
        Meter real = new WaterMeter();
        Meter viaConstructor = new Meter(real);
        Meter viaClone = real.clone();
        real.log[0] = 31;
        System.out.println(viaConstructor.unit() + " " + viaConstructor.log[0]);
        System.out.println(viaClone.unit() + " " + viaClone.log[0]);
        System.out.println("constructors run: " + Meter.built);
    }
}

What is asked.

All three lines.

Idea.

new Meter(...) builds what its name says. clone() builds the runtime class.

  1. new WaterMeter() runs Meter(30), so the counter is 1.
  2. new Meter(real) builds a plain Meter with its own array, and the counter becomes 2.
  3. real.clone() builds a WaterMeter without a constructor. It shares the array.
  4. real.log[0] = 31 is seen by the clone, not by the constructed copy.
  5. Output: plain 30, litres 31, constructors run: 2.

Answer.

plain 30, litres 31, constructors run: 2

Common mistake.

Expecting the constructed copy to be a WaterMeter.

Copy constructor against clone

Constructor

Builds a Meter, whatever m really is. Runs your constructor code.

Meter two = new Meter(m);

Clone

Builds the runtime class of m. Runs no constructor.

Meter two = m.clone();

The difference. The class is named after new on the left; on the right the object itself decides.

new Type(x) fixes the class in the source. x.clone() with super.clone() keeps the class of x.

When This Breaks

"A copy constructor gives a faithful copy" breaks for subclass objects: the extra fields and overridden methods of the subclass are left behind. It also breaks for null: new Playlist((Playlist) null) throws NullPointerException at the first field read.

Practise this topic →

Weeks covering this topic

Other Java topics