Copy Constructor and Factory Method in Java

In this post, we will discuss how to copy objects in Java using copy constructor. We will also cover 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 to always 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 use 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. Object.clone() method will result in 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.


Download   Run Code


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

Copy Factory –

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


Download   Run Code

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)


Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

Notify of