What is a Copy Constructor In Java?

In the current article about what is a copy constructor in java we will learn and focus about copy constructor and cover all related questions that arose for copy constructor in detail with suitable examples.

First, Let’s categorized this article in following learning steps:

1. What is a copy constructor in java?

A Copy Constructor is a constructor mechanism in a Java class that is used to create an object initialized with another java class object of the same class. It means we can create duplicates of existing objects having the same values.

Suppose we have fan object with parameter like color: blue type : Ceiling Now we need a different object (Instance) with the same attributes like type Ceiling & color blue.

In such case we can use Copy Constructor to make duplicate copy of already created object pointing to different memory location.

How? Let's see and learn in this Copy Constructor program

Let’s understand in this way. As we know normal java class constructor ( parameterized constructor ) used to initialize its instance variables by passing initial values while creating objects.

Suppose we have Employee Constructor such as

public Employee(String name, int empId, String department) {
    this.name = name;
    this.id = empId;
 this.department = department;

}
    

We can create Employee object by initializing it’s attribute using above parameterized constructor as below

Employee emp = new Employee("John", 10001, "Hr");

Create Copy Constructor using already created object in following way

Employee empCopyObj = new Employee(emp);

What is a copy constructor in java

As we see, it doesn’t require initialization for each class attribute like a parameterized constructor .What we just pass an already created object as a parameter to initialize its instance attributes the same as passed objects. Therefore empCopyObj will contain the same information as emp object.

emp empCopyObj (Object created by Copy constructor)
name John John
id 10001 10001
department Hr Hr
Memory Address Xyz Abc

Note: Memory address Xyz & Abc is not a real memory address. Mentioned Just for reference only to distinguish memory addresses for both objects.

Copy constructor in Java Program. Refer this Copy constructor example for better understanding

Refer Following example for copy constructors in Java. 

public class Employee {

    private String name;

    private int empId;

    private String department;

    public Employee(String name, int employeeID, String department) {
        this.name = name;
        this.empId = employeeID;
        this.department = department;
    }

    public Employee(Employee emp) {
        this.name = emp.name;
        this.empId = emp.empId;
        this.department = emp.department;
    }

    public void showEmployeeInfo() {

        System.out.println("Name : " + this.name);
        System.out.println("EmployeeID : " + this.empId);
        System.out.println("Department : " + this.department);
    }

    public static void main(String[] args) {

        Employee emp = new Employee("John", 10001, "HR");

         System.out.println("Display Employee details  initialized via constructor.");
        // Show Employee details  initialized via constructor 
        emp.showEmployeeInfo();

        
        System.out.printf("Object emp Reference: %s\n",emp);
        
        
        Employee empCopyObject = new Employee(emp);

         System.out.println("Display empCopyObject details  initialized via copy constructor ");
        // Show Employee details  initialized via copy constructor 
        empCopyObject.showEmployeeInfo();
        
         System.out.printf("Object empCopyObject Reference: %s\n",empCopyObject);
        
        
       System.out.println("Update employee ID information from 10001 to 9999 ");
       
       emp.empId = 9999;
        
       System.out.println("Display empCopyObject details after updating emp object employeeID value ");
       
        empCopyObject.showEmployeeInfo();
    }

    

Output:

Display Employee details  initialized via constructor.
Name : John
EmployeeID : 10001
Department : HR
Object emp Reference: javaapplication.Employee@3fee733d

Display empCopyObject details  initialized via copy constructor 
Name : John
EmployeeID : 10001
Department : HR
Object empCopyObject Reference: javaapplication.Employee@5acf9800

Update employee ID information from 10001 to 9999 
Display empCopyObject details after updating emp object employeeID value 
Name : John
EmployeeID : 10001
Department : HR
    

2. Why do we need a copy constructor?

As we have seen in the above example, the copy constructor requires only an already created object as param to initialise it’s instance variables. Therefore we don’t need to create objects by passing all instance variable values as constructor arguments for initialization.

Here is list of advantage of using copy constructor

  • A copy constructor is very convenient to use, especially for complex object structures with multiple instance attributes.
  • We can use a copy constructor as an alternative to the Object.clone() method.
  • Constructor is implicitly called when an instance is created using a new keyword.
  • Typecasting is NOT required in copy constructor whereas typecasting is needed in clone() method because clone returns object type which further requires conversion to object reference.

3. Copy of a Reference is NOT Equal to a Copy of the Object.

Let’s understand with an example:

 Employee emp = new Employee(“John”, 10001);
 Employee copyObject = emp;

Here Reference of object created as new Employee(“John”, 10001) has been assigned to CopyObject. It means both references emp & copyObject pointing to the same object.

Conclusion: Here both objects refer to the Same memory address therefore CopyObject instance variable data will be changed/modified along with emp object param/attribute changes.

Let’s understand this concept about reference copy by following program

public class Employee {

    private String name;

    private int empId;

    private String department;

    public Employee(String name, int employeeID, String department) {
        this.name = name;
        this.empId = employeeID;
        this.department = department;
    }

 
    public void showEmployeeInfo() {

        System.out.println("Name : " + this.name);
        System.out.println("EmployeeID : " + this.empId);
        System.out.println("Department : " + this.department);
    }

    public static void main(String[] args) {

        Employee emp1 = new Employee("John", 10001, "HR");


        System.out.println("Display Object emp1 details:");
        // Show Employee details  initialized via constructor 
        emp1.showEmployeeInfo();

        
        Employee emp2 = emp1;

        emp1.empId = 555;
        emp1.name = "Peter";

        System.out.println("Display emp2 information after modified attributes of object emp1");
        emp2.showEmployeeInfo();
        
        
    }
}


    

Review Output for above program:

Display Object emp1 details:
Name : John
EmployeeID : 10001
Department : HR
Object emp1 Reference: javaapplication.Employee@3fee733d
Display emp2 details after changing of object emp1 attributes
Name : Peter
EmployeeID : 555
Department : HR
Object emp2 Reference: javaapplication.Employee@3fee733d


    

Here both emp1 & emp2 pointing same location as Employee@3fee733d. Please try at your end by running above program and play around with different cases.

Question? Feel free to raise your query. We will be happy to assist..