Why do we need a copy constructor and when should we use a 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
raja
Published on 24-May-2019 13:48:11
Advertisements