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?

Like C++ and JavaScript, there is no easy and direct way of copying objects in Java programming language. The built-in clone capability is poorly designed and is rarely the best alternative.

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.

package com.roytuts.java.copy.constructor;

public class User {

	private String name;
	private String address;

	public User(String name, String address) {
		this.name = name;
		this.address = address;
	}

	public User(User user) {
		this.name = user.name;
		this.address = user.address;
	}

	@Override
	public String toString() {
		return "User [name=" + name + ", address=" + address + "]";
	}

}

Test Class

Write a class with main method to test copy constructor.

package com.roytuts.java.copy.constructor;

public class CopyConstructorExample {

	public static void main(String[] args) {
		System.out.println("Without using copy constructor");
		
		User user = new User("Soumitra", "https://roytuts.com");
		
		System.out.println(user);
		
		System.out.println();
		
		System.out.println("Using copy constructor");
		
		User user2 = new User(user);
		
		System.out.println(user2);
	}

}

Testing the Program

Running the above example will give you below output:

Without using copy constructor
User [name=Soumitra, address=https://roytuts.com]

Using copy constructor
User [name=Soumitra, address=https://roytuts.com]

Analysis

The statement,

User user = new User("Soumitra", "https://roytuts.com");

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

The statement,

User user2 = new User(user);

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.

Leave a Reply

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