Thursday, 2 February 2017

HOW TO CREATE IMMUTABLE CLASS IN JAVA

To create immutable class we have to take care of few things like –
  • ·        The class should not be further extended.
  • ·       We cannot change the value of the instance variable after the creation of an object.
  • ·        There should not be any setter method for that variable, so that we cannot change its value


Example –
public final class String1{
          final String empid;
          public String1(String empid) {
                   this.empid = empid;
          }       
          public String getEmpid() {
                   return empid;
          }
          public static void main(String[] args) {
                   String1 s = new String1("A101");
                   System.out.println(s.getEmpid());                  
          }
}

Output –
A101

Note – This is one of the import question which is asked during an interview.


Example – To create immutable class which includes mutable class
public final class String1{
          private final String name;
          private final Address a;    
                  
                   public String1(String name, Address a) {
                   super();
                   this.name = name;
                   this.a = a;
          }
                   public String getName() {
                             return name;
                   }
                   public Address getA() throws CloneNotSupportedException {
                   return (Address)super.clone();
          }
                   public static void main(String[] args) {
                             Address a1 = new Address();
                             a1.setStreet("abc");
                             String1 s = new String1("rakesh", a1);
                             System.out.println(s.getName());
          }
}

public class Address {
          private String street;
          public String getStreet() {
                   return street;
          }
          public void setStreet(String street) {
                   this.street = street;
          }       
}


Note – Even we store the data of mutable class in final field, but it can be modified internally, if the internal data is returned to the client. Hence in order to maintain immutability we should return the copy of that particular object not the original data.

No comments:

Post a Comment