Why do we need copy constructor and when should we use copy constructor in java

Copy constructors, by convention, should provide a deep copy of objects. As already mentioned by other answers, the main convenience provided by copy constructors is when your object becomes too complex. Note that java.lang.Cloneable provides an (almost) similar declaration.

But there are a number of advantages to using copy constructors over the Cloneable interface.

  1. Cloneable as an interface does not actually provide any methods. For it to be effective, you still need to override the clone method of java.lang.Object. This is quite a counterintuitive use for an interface.

  2. clone returns an Object. For it to be of any use, you still need to typecast. This is awkward and could lead to runtime errors.

  3. The clone method is poorly documented. For clone, things can get messed up if you have final fields pointing to mutable objects.

  4. Most importantly, copy constructors can take in and deep copy instances of subclasses. IMO, this is where copy constructors really shine.

There are more advantages (see Joshua Bloch's Effective Java 2e) but these are the points which I have found most pertinent to what I have worked on so far.

[1] Nothing in the Java language actually provides a default construct for deep copying. At most, objects can just tell programmers that they can be deep copied by, say, implementing Cloneable or providing a copy constructor.


There are 2 good reasons for using a copy constructor instead of the constructor passing all parameters :

  1. when you have a complex object with many attributes it is much simpler to use the copy constructor
  2. if you add an attribute to your class, you just change the copy constructor to take this new attribute into account instead of changing every occurence of the other constructor