Showing posts with label immutable classes in java. Show all posts
Showing posts with label immutable classes in java. Show all posts

Monday, 21 July 2014

Immutable objects - Java

Immutable Class - 

An immutable class is one whose state can not be changed once created


Rules/Guidelines to make a class immutable in java 


  •  Donot provide / remove all the setter methods of the member variables in the class
  •  Make the class as final . If we donot make it final child class can have setter implementation. 
  •  Make all the fields final and private 

import java.util.Date;

public final class ImmutableClass
{
 private final Integer test1;

 private ImmutableClass(Integer test1)
 {      this.test1 = test1;
 }
     public static ImmutableClass createNewInstance(Integer fld1, String fld2, Date date)
 {
  return new ImmutableClass(fld1, fld2, date);
 }

 //Provide no setter methods

 public Integer getTest1() {
  return test1;
 }