Shallow and deep copies, seen as arrows between objects.
Open the interactive lessons →Cloning and Copy Constructors past questions
Contents
- A second name or a second object
- What a shallow clone shares
- Cutting the shared arrows: deep cloning
- Who may be cloned: the contract and inheritance
- 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.
super.clone() doesIt 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.
new Lamp(40)makes object 1.same = halladds a name for object 1.hall.clone()makes object 2 withwattsequal to 40.same.watts = 60writes object 1.spare.watts += 5writes object 2: 40 becomes 45.- 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.
The program prints 60 60 45 and true false.
- The third object line becomes
Lamp spare = same;. What are the two lines now?
It prints65 65 65andtrue true.. Only one object exists. Both writes land in it. Lamp spare = hall.clone();moves belowsame.watts = 60;. What is the first line?
It prints60 60 65andtrue false.. The clone copies the values that exist when it is called, sosparestarts at 60.spare.watts += 5;becomeshall.watts += 5;. What is the first line?
It prints65 65 40andtrue 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.
new Badge("Anu", 2)runs the constructor and printsbuilt Anu.duplicate()is a method of the class that returnssuper.clone(); its name is free. The callfirst.duplicate()copies both fields. The constructor does not run, so no secondbuiltline appears.third = secondadds a name for box 2.second.owner = "Bela"assigns a field of box 2. Box 1 still refers to the textAnu.third.floor = 7writes box 2.first.floor++makes box 1 hold 3.- 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.
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
- One
Lampexists. It has a number and a reference to a text. super.clone()makes a new object of the same runtime class. No constructor runs.- A primitive field is copied as a value. The two objects now hold their own 40.
- A reference field is copied as a reference. No second
Stringis made. - The cast result is stored in
spare.hall == spareisfalse. - Changing a number in the copy leaves the original alone.
"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?
- The clone has its own
kilos,labelandpocketsfields. The last two hold the same arrows as inmine. yours.kilos = 15assigns a field of the copy only.yours.label.city = "Pune"follows the arrow and writes in the one shared label.yours.pockets[1] = 8writes in the one shared array.mineshows 12, Pune, 8.yoursshows 15, Pune, 8.
Answer.
12 Pune 8 then 15 Pune 8
Common mistake.
Printing Goa for the original because a clone was made.
The program prints 12 Pune 8 and 15 Pune 8.
yours.label.city = "Pune";becomesyours.label = new Label("Pune");. What does the first line print?
It prints12 Goa 8, then15 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 prints12 Pune 30and15 Pune 30.. Sharing works in both directions: a write through the original is seen by the copy. Suitcase yours = mine.clone();becomesSuitcase yours = mine;. What does the first line print?
Both lines print15 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.
- After the clone,
aandbshare the array{4, 4}and the builderred. b.marks[0] = 9changes the shared array to{9, 4}.b.colour.append("-blue")changes the shared builder tored-blue.b.marks = new int[] {0, 0}moves onlyb's arrow. The next write givesbthe array{0, 6}.b.colour = new StringBuilder("green")moves the other arrow ofb.areads9 4 red-blue;breads0 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
- One suitcase points at one label and one array.
- The clone copies three fields. Both suitcases point at the same label and array.
- A number belongs to one object only.
mine.kilosstays 12. yours.label.cityfollows the arrow and writes in the shared label.minesees Pune.- The array is shared too.
mineprints12 Pune 8andyoursprints15 Pune 8.
"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.
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().
clone()starts with a shallow copy.motor.clone()gives the copy a secondMotor.route.clone()gives the copy a second array.- The three later writes use
band touch onlyb's own objects. akeeps A1, 900, 2.bshows B2, 1200, 3.
Answer.
A1 900 2 then B2 1200 3
Common mistake.
Letting 1200 appear in a out of habit from shallow questions.
The program prints A1 900 2 and B2 1200 3.
- The line
copy.route = route.clone();is deleted. What is the first line?
It printsA1 900 3, thenB2 1200 3.. The array is shared again, so the route write is seen bya. - Only the line
copy.motor = motor.clone();is deleted. What is the first line?
It printsA1 1200 2, thenB2 1200 3.. One motor serves both drones. - The first drone is built with
nullas its motor. What happens when it is cloned?
It throwsNullPointerExceptioninsideclone()..motor.clone()calls a method onnull. A guard such asmotor == 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.
super.clone()copies the arrow to the list.- A fresh list is assigned to the copy.
- The loop adds a clone of each plant, so four
Plantobjects exist. south.plants.remove(0)takes the fern out of the copy's list only.get(0)is now the copy's own mint, so its height becomes 25.addchanges only the copy's list.- 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
- The original drone owns one motor and one route array.
- Step one is
super.clone(). For a moment the copy is shallow: both arrows are shared. copy.motor = motor.clone()makes a second motor and moves only the copy's arrow.- The same is done for the array. Now no mutable object is shared.
- Writes through
bstay in the copy.astill 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.
seats.clone()makes a new outer array holding the same two row arrows.plan[0][0] = 7writes in the shared first row.plan[1] = new int[] {8, 8}assigns a slot of the new outer array only.seatsreads 7 and 2;planreads 7 and 8.
Answer.
7 2 then 7 8
Common mistake.
Calling clone() on the outer array deep.
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
| Condition | Checked by | If missing |
|---|---|---|
A clone method you are allowed to call (Object.clone is protected, so classes usually declare a public one) | compiler | compilation error |
CloneNotSupportedException caught or declared | compiler | compilation error |
The runtime class implements Cloneable | running program, inside Object.clone | CloneNotSupportedException 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.
- The file compiles: both
clonemethods are public and the exception is caught. new Stamp().clone()succeeds, sostamp 5is printed.new Token().clone()reachesObject.clone, which finds noCloneablelabel and throws.- The line printing the token is skipped; the
catchprintsrefused. - The program goes on and prints
end.
Answer.
stamp 5, refused, end
Common mistake.
Calling the missing implements Cloneable a compilation error.
The program prints stamp 5, refused, end.
Tokenis declaredimplements Cloneable. What prints now?
It printsstamp 5,token 2,end.. Both runtime classes pass the test, so thecatchnever runs.Stamplosesimplements CloneableandTokenstill lacks it. How many lines print?
It printsrefusedandend.. The first clone already throws, so the rest of thetryis skipped.- The
tryandcatchare removed andmaindeclares 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
new Stamp().clone()is about to run. The compiler already accepted every line.- Inside
Object.clonethe runtime class is tested: doesStampimplementCloneable? Yes. - A copy is made and
stamp 5is printed. Tokenhas aclonemethod but lacksimplements Cloneable.CloneNotSupportedExceptionleaves the call. The rest of thetryis skipped andrefusedis printed.- Execution continues after the
catchand printsend.
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.
one.clone()runs the inherited method.Object.clonesees the runtime classOrgan, which isCloneablethrough its parent.- The result is a new
Organ:sound()returnschordand its class name isOrgan. pipeswas copied (8). The writetwo.volume = 9leavesone.volumeat 3.two instanceof Cloneableistrue.
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.
- The clone is a
Tent, and every field is first copied shallowly. - The parent then replaces
poleswith a new array. - No code replaces
pegs, so it stays shared. ashows 2 and 10;bshows 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.
"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?
- None of the three assignments creates an object, so the builder and the array are shared.
copy.mood.append("-night")changes the shared builder.copy.plays = 4assigns a number field of the new object only.copy.seconds[1] = 95writes in the shared array.baseshows calm-night, 95, 0.copyshows 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.
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 printscalm-night 180 0, thencalm-night 95 4.. The new object has its own array. The builder is still shared. Playlist copy = new Playlist(base);becomesPlaylist copy = base;. What are both lines?
Both printcalm-night 95 4.. No constructor runs and only one object exists.- The line
this.plays = source.plays;is deleted andbase.plays = 6;is added before the copy is made, withcopy.plays = 4;removed. What are the two lines?
It printscalm-night 95 6, thencalm-night 95 0.. A field that the copy constructor never assigns keeps its default.
A copy constructor does only what you wrote
- One playlist and one array of track lengths. The
moodfield is left out of this picture. new Playlist(base)creates an object with default fields, then runs your constructor withsourceset tobase.- A number is copied as a value. Each playlist now holds its own 0.
- This line copies the reference, not the array. This copy constructor is shallow.
- The new count stays in
copy. A write into the array is seen bybasetoo.
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.
new WaterMeter()runsMeter(30), so the counter is 1.new Meter(real)builds a plainMeterwith its own array, and the counter becomes 2.real.clone()builds aWaterMeterwithout a constructor. It shares the array.real.log[0] = 31is seen by the clone, not by the constructed copy.- 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.
"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.
Weeks covering this topic
- Week 2: Data types, control flow, classes and objects
- Week 8: Cloning, type inference, higher-order functions, streams