Sunday 11 December 2016

write immutable class in Java with example

How to write immutable class in Java

Some points we need to follow, which helps to make a class immutable in Java :

1. State of immutable object can not be modified after construction, any modification should result in new immutable object.
2. All fields of Immutable class should be final.
3. Class should be final in order to restrict sub-class for altering immutability of parent class.

So our immutable class have all private and final variables and a constructor to initialize the variables during object creation. All final variables can be initialized inside constructor only once during object creation that can't be changed latter. our immutable class does not provide setter method but have only getter method to access the initialized variables. 

Example

Simplest approach for making a class immutable, including it's making final class to avoid putting immutability at risk due to Inheritance and Polymorphism.



public final class Contacts {

    private final String name;
    private final String mobile;

    public Contacts(String name, String mobile) {
        this.name = name;
        this.mobile = mobile;
    }
  
    public String getName(){
        return name;
    }
  
    public String getMobile(){
        return mobile;
    }

}

Singleton design pattern and preventing its cloning

Singleton :- Singleton design pattern is used to create only single object of the class. we can say to avoid the multiple object creation and limiting the number of objects to one. 

Prevent Object Cloning :- We can prevent the object cloning of singleton class by implementing the Cloneable interface and forcefully throw an exception 'throw new CloneNotSupportedException();' inside overridden clone() methods as written in below example-   

public class MySingletonTest implements Cloneable {

 private static MySingletonTest mSingletonTest = null;

 private MySingletonTest() {

  System.out.println("Sanjaya verma");

 }

 public static MySingletonTest getInstance() {

  if (mSingletonTest == null) {

   mSingletonTest = new MySingletonTest();

  }

  return mSingletonTest;

 }


 @Override
 protected Object clone() throws CloneNotSupportedException {
 // Here forcefully throw an exception to prevent the object cloning

  throw new CloneNotSupportedException();

  //return super.clone();

 }



 public static void main(String[] args) {

  MySingletonTest t1=new MySingletonTest(); 

  try {

       // call to overridden clone method which throw an exception

   MySingletonTest t2=(MySingletonTest)t1.clone(); 
   // compiler will not reach to this line.
   System.out.println(t2); 

  } catch (CloneNotSupportedException e) {

   // TODO Auto-generated catch block

   e.printStackTrace();

  }

 }

}



Output-

Sanjaya verma

java.lang.CloneNotSupportedException

 at com.sanjay.java.interview.MySingletonTest.clone(MySingletonTest.java:21)

 at com.sanjay.java.interview.MySingletonTest.main(MySingletonTest.java:30)