QuizCure
Find Available Solution Here!

What is a Copy Constructor In Java?

Deepak Apr 18, 2024

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

First, Let's categorize this article in the following learning steps:

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 an object with parameters 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 copies of already created objects pointing to different memory locations.

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

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

Suppose we have an Employee Constructor such as

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

}
    

We can create an Employee object by initializing its attribute using the 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. 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 an 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 the 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 the 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 the constructor.
Name: John
EmployeeID: 10001
Department: HR
Object emp Reference: javaapplication.Employee@3fee733d

Display empCopyObject details  initialized via the 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
    

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 a parameter to initialize 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 a list of advantages 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.

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 point 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 the 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 the above program and playing around with different cases.

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

Was this post helpful?

Send Feedback

Connect With QuizCure


Follow Us and Stay tuned with upcoming blog posts and updates.

Contributed By

Deepak

Deepak

QC STAFF
51 Posts
  • PHP
  • JAVA
  • PYTHON
  • MYSQL
  • SEO

You May Like to Read

Scroll up