What is a copy constructor, and when do you need to write one rather than relying on the default behaviour?
A copy constructor is a constructor that takes an object of the same class and makes a new object with the same values. You need one when the default copying is not enough.
And what does the default copying do? It copies the reference, not the contents. So the two names point at the same object in the heap.
public class Main {
public static void main(String[] args) {
Playlist original = new Playlist();
original.add("Sultans of Swing");
Playlist copy = original; // the same object, not a copy
copy.add("Fly Me to the Moon");
System.out.println(original.size()); // 2, they are the same
}
}
And when do you need to write a copy constructor? There are three reasons.
the reason why
-------------------------------------- --------------------------------
the class holds a mutable field a plain copy would share it
the class has an identity that must the copy needs a new identity
not be shared
the class has a field that must not the copy has to keep it
change
And the most common case is the first one. If the class holds a list and you copy the object with the plain assignment, then both objects share the same list. So adding to one of them changes the other one too, and that is almost never what the caller wanted.
public class Playlist {
private final java.util.List<String> tracks = new java.util.ArrayList<>();
public void add(String track) {
tracks.add(track);
}
public int size() {
return tracks.size();
}
}
So the copy constructor has to make a new list and copy the values into it.
And there is a second reason that is worth knowing about, and it is about immutability. A class with only final fields is safe to share, because nothing can change it after the constructor. A class with a mutable field is not safe to share, so it needs a copy constructor that makes a proper copy.
So the rule to remember is this. A copy constructor is needed whenever the class holds something that can be changed.
The next two questions in this topic show the list version and what the default copy actually copies.