title: Why do we need copy constructor and when should we use copy constructor in java
body: <p>I was going through Copy Constructors, I have gone through the links in stack over flow and others as well. But i am not clear on the following points.</p>
  
  <ol>
  <li>Why do we need a Copy Constructor</li>
  <li>When do we need a Copy Constructor</li>
  </ol>
  
  <p>I mean what is the exact situation or scenario we would need to use Copy Constructor. Can some one explain with an example or point out links so that i can go through and understand them in clear.</p>
  
  <p>Following are the links i have gone through to get an understanding of what is a copy constructor.</p>
  
  <p><em><a href="http://www.programmerinterview.com/index.php/java-questions/how-copy-constructors-work/" rel="noreferrer">http://www.programmerinterview.com/index.php/java-questions/how-copy-constructors-work/</a></em></p>
  
  <p><em><a href="https://deepeshdarshan.wordpress.com/2013/12/05/copy-constructors-in-java/" rel="noreferrer">https://deepeshdarshan.wordpress.com/2013/12/05/copy-constructors-in-java/</a></em></p>
  
  <p>The second link explains 'why' and 'where' the copy constructor is to be used. But still i am not clear on it.</p>
  
  <p>Below is my class Employee.java</p>
  
  <pre><code>package com.test;
  
  /**
   * @author avinashd
   *
   */
  public class Employee {
  
      private String rollNo;
      private String name;
  
      //constructor
      public Employee(String rollNo, String name){
  
          this.rollNo = rollNo;
          this.name = name;
      }
  
      //copy constructor
      public Employee(Employee employee){
  
      this.rollNo = employee.rollNo;
      this.name = employee.name;
  
      }
  
      public String getRollNo() {
          return rollNo;
      }
  
      public void setRollNo(String rollNo) {
          this.rollNo = rollNo;
      }
  
      public String getName() {
          return name;
      }
  
      public void setName(String name) {
          this.name = name;
      }
  }
  </code></pre>
  
  <p>Copy Constructor is used to create and exact copy of an object with the same values of an existing object.</p>
  
  <p>Say for example we have an Employee with values as <code>rollNo: 1</code> and <code>name: avinash</code>. Copy Constructor would create a similar object with values as <code>rollNo: 1</code> and <code>name: avinash</code> . But both are 2 different objects and changes to the values of on object will not affect another object.</p>
  
  <p>The Question here is </p>
  
  <p>When we have a constructor such as  </p>
  
  <pre><code>public Employee(String rollNo, String name){
      this.rollNo = rollNo;
      this.name = name;
  }
  </code></pre>
  
  <p>to create an object. We can call the same constructor to create another object. But why do we need to call copy constructor.When do we need to call it ?. Please explain</p>