title: Immutability property in java
body: <p>I know that when it comes to passing objects in java, the reference of object is passed as value. So what ever changes you make to that object is reflected in the original object as well. To avoid this we make use of immutability property in java.</p>
  
  <p>So my question is, I have created an <strong>immutable</strong> class <code>Employee</code>, When I pass an object of this <code>Employee</code> class to some method in other class, I don't want that method to make any changes to this object. Even if it does, I don't want the changes to be affected to the original object created in the calling class. </p>
  
  <p>Here is my sample code.</p>
  
  <pre><code>public final class Employee {
      int employeeId;
  
      public int getId() {
          return employeeId;
      }
  
      public void setId(int id) {
          this.employeeId = id;
      }
  
  }
  
  public class Worker {
      public static void process(Employee f, Employee g){
          int c = f.getId();
          f.setId(g.getId());
          g.setId(c);
      }
  }
  
  public class ImmutabilityTest{
  
      public static void main(String[] args) {
          Employee teamMember = new Employee();
          Employee teamLead = new Employee();
          teamMember.setId(5);
          teamLead.setId(10);
          System.out.println("Before process "+teamMember.getId() + " " + teamLead.getId());
          Worker.process(teamMember, teamLead);
          System.out.println("After process "+teamMember.getId() + " " + teamLead.getId());
      }
  }
  </code></pre>
  
  <p>The output will be </p>
  
  <pre><code>Before process 5 10
  After process 10 5
  </code></pre>
  
  <p>Is there any way to avoid the change in the values of the member variables of the Employee class ? (apart from making them <code>final</code>)If not then how are we actually exploiting the <strong>Immutability</strong> property in java in user defined class ?</p>
  
  <p>Any suggestions/opinions/pointers are appreciated ! Thanks..</p>