Need and Usage of Copy Constructor in Java



A copy constructor is a parameterized constructor and it can be used when we want to copy the values of one object to another.

Example:

class Employee {
   int id;
   String name;

   Employee(int id, String name)
   {
      this.id = id;
      this.name = name;
   }
   Employee(Employee e)
   {
      id = e.id;
      name = e.name;
   }
   void show()
   {
      System.out.println(id + " " + name);
   }
   public static void main(String args[])
   {
      Employee e1 = new Employee(001, "Aditya");
      Employee e2 = new Employee(e1);
      e1.show();
      e2.show();
   }
}

In the above code, e1 is passed as an argument to the second constructor. Thus values of e1 are copied into object e2.

Output:

1 Aditya
1 Aditya
Updated on: 2019-07-30T22:30:26+05:30

452 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements