This post will discuss how to copy objects in Java using a copy constructor. We will also cover the Factory method approach that does the same.

Copy Constructor

A copy constructor is a special constructor for creating a new object as a copy of an existing object. It defines the actions performed by the compiler when copying class objects. It is a very good practice always to have a copy constructor defined in the class.

It has just one argument that is usually a reference to an object of the same type as is being constructed. In other words, it accepts a parameter that is just another instance of the same class.

Any copy constructor implementation usually uses an assignment operator = for primitive & immutable fields and a new operator for mutable fields & objects for copying objects in Java. This will result in a Deep Copy.

Copy constructors are the preferred way of copying objects in Java, as opposed to clone() Method. There are several advantages of using copy constructor over the clone() method:

  1. It is much more simpler to use the copy constructor on a complex object with many fields.
  2. Default implementation of Object.clone() returns a shallow copy. Copy constructors can easily return deep copies for non-complex objects.
  3. Copy constructors don’t force us to implement Cloneable or Serializable interface.
  4. Object.clone() throws CloneNotSupportedException when class fails to implement Cloneable interface. Copy constructors don’t throw any such exception.
  5. Object.clone() returns an Object and typecasting is needed to assign the returned Object reference to a reference to an object. No such typecasting is needed for Copy constructors.
  6. Copy constructors gives us complete control over object initialization, unlike default implementation of Object.clone(). We can have mix of deep and shallow copies for different fields in the class.
  7. The Object.clone() method will result in a compilation error if we try assign a value to a final field on the object received from the superclass. Copy constructors, on the other hand, will allow us to assign a value to a final field just once.

The following program demonstrates it:

Download  Run Code

Output:

Using Copy Constructor: [Jon Snow, 22, [Maths, English, Science]]
[Maths, English, Science]

Copy Factory

We can also use the static copy factory method to essentially do the same thing as the copy constructor method. This approach is shown below:

Download  Run Code

That’s all about the copy constructor and factory method in Java.