Writing an immutable class is generally easy but there can be some tricky situations. Follow the following guidelines:
1.A class is declared final (i.e. final classes cannot be extended). public final class MyImmutable { � }
2.All its fields are final (final fields cannot be mutated once assigned).
3.Do not provide any methods that can change the state of the immutable object in any way � not just setXXX methods, but any methods which can change the state.
4.The �this� reference is not allowed to escape during construction from the immutable class and the immutable class should have exclusive access to fields that contain references to mutable objects like arrays, collections and mutable classes like Date etc by:
�Declaring the mutable references as private. �Not returning or exposing the mutable references to the caller (this can be done by defensive copying)
In Java, a class is immutable if no methods are provided to mutate class level variables. Basically its easier to make a class immutable than mutable. Just don't provide any Mutator methods.
Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter