Tuesday, July 19, 2016

How to create Immutable class in java?

Most of the interview, we can expect this question. In Nutshell, java have lot of immutable classes like String, Integer, Float etc.,

Please remember below points to make your class as immutable.
  • Make your class as Final, So that other can not extends it, means cannot create sub class. 
  • Declare instance variable as Final with private modifier, so that it can not change once initiated.
  • Don't implement setter methods.
  • Finally, don't provide any method which will change the behavior of state of the object.

Example :

public final class JavaHit{ 
    final String name;  
  
public JavaHit(String name){  
    this.name=name;  
  }  
  
public String getName(){  
    return name;  
  }    


Benefits of Immutable class:
  • It will be helpful in synchronization environments, since its thread-safe.
  • Internal state of immutable class will be fine, even you get any exception.
  • It will be good to work with Map Keys and set elements, since typically it will not change once its created.

No comments:

Post a Comment