How to write Immutable class in Java?
What is Immutability?
1. Immutability means read only, which means once you create Immutable object, you can't change it's state.
How to make class Immutable?
To make any class immutable, you have to apply following steps
1. Make the class as final, so that no other classes can extend.
2. Declare all the fields as private, so that no other classes can access directly.
3. Declare all the fields as final, and initialize those from constructor.
4. Provide getter methods for the private fields, But make sure to return copy of the field, not the actual field. if you return actual reference, it's state can be changeable.
Advantages Of Immutable Objects:
1. One main advantage for using immutable objects is Thread Safety, because the values cannot ever change,
they can be freely passed from thread to thread without ever needing locking.
2. This means that, because there is no locking with synchronized blocks, there is no bottleneck where
multiple threads need to wait for a single mutable value to be available.
3. Usually when you have a need to update the value in an immutable object, you make a new copy of the object with the updated value.
Examples of Immutable classes
1. String
2. All Primitive Wrapper classes such as Integer, Float, Double etc.
Sample Programs:
/** * This class is to demonstrate Immutability in Java * @author Sreenath * */ public final class ImmutableClass { // state private final int number; private final StringBuilder sbr; public ImmutableClass(int number, StringBuilder sbr) { this.number = number; this.sbr = sbr; } // just return number public int getNumber() { return number; } // create a copy of sbr and return public StringBuilder getSbr() { StringBuilder sbrCopy = new StringBuilder(sbr); return sbrCopy; } }Test Program
public class ImmutableClassTest { public static void main(String[] args) { StringBuilder sbr = new StringBuilder("Test"); ImmutableClass ic = new ImmutableClass(5, sbr); StringBuilder sbr2 = ic.getSbr(); // checking equality System.out.println("comparing String builders " + (sbr == sbr2)); // changing sbr2 sbr2.append("Modified"); // print old sbr and new sbr System.out.println(ic.getSbr().toString()); System.out.println(sbr2.toString()); } }
Comments
Post a Comment