Copy Constructor in Java

What is Copy Constructor

Sometimes a programmer wants to create an exact but separate copy of an existing object so that subsequent changes to the copy should not alter the original or vice versa. This is made possible using the copy constructor.

A copy constructor is a constructor that creates a new object using an existing object of the same class. Copy constructor takes single argument which is of the type as the class itself in which the copy constructor is implemented.

For example, let us assume a class namely User and it has a constructor called copy constructor which expects only one argument of type User.

Why does it require

Copy constructors are widely used for creating duplicate objects known as cloned objects. Duplicate object in the sense that the object will have the same characteristics of the original object from which duplicate object is created. But we have to ensure that both original and duplicate objects refer to different memory locations.

Where does it need to be implemented

It is our responsibility to implement a copy constructor in our class in the right way. As mentioned above, it is used to duplicate objects. So we are free to use copy constructors instead of clone method in Java.

How does it get implemented

Copy constructors are implemented for deep cloning and shallow cloning. Both these cloning techniques can be achieved by overriding the clone method in java. Shallow cloning is the default cloning implementation in Java and we just need to override the clone method. But deep cloning has to be implemented as per our requirements.

Salient features of Copy Constructor

It provides an attractive alternative to the rather pathological clone method
It can be easily implemented
It simply extracts the argument’s data, and forward to a regular constructor
Copy Constructor is unnecessary for immutable objects

When you pass an instance of a particular class to copy constructor, it returns a new instance of the same class with all values copied from the parameter instance.

Example
Create below User class. Notice how constructor passes an argument of type User class.

Output

The statement,

creates a User object and invokes the constructor User(String name, String address) which initializes values name and address with values “Soumitra” and “www.roytuts.com” respectively and returns the reference to user variable.

The statement,

invokes a copy constructor User(User user) and initializes the instance variables name and address of the newly created User object and returns its reference to the user2 variable.

Thanks for reading.

Soumitra

Software Professional, I am passionate to work on web/enterprise application. For more information please go to about me. You can follow on Twitter. You can be a friend on Facebook or Google Plus or Linkedin

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.