How to make a class immutable with Date object in it?

The simplest thing to do here to make the class immutable is to create a defensive copy of the Date object (when it is passed in the construction parameters). Then don't provide any setters as well. Like this no reference to the Date field in the class is visible to code outside this class and thus the Date can't be modified.

See Tom's comment for required getter characteristic! Thanks for the addition.

(Getter should return a copy of the date field as well, since Date itself is mutable, and changing the returned field from the getter will change the class's field as well.)

For more information and details: http://www.informit.com/articles/article.aspx?p=31551&seqNum=2


I suggest to create a wrapper class around the date which you are using and dont provide any setters or any method which can actually change the value.

For making it immutable you need to consider following things :

  1. You need to make sure that the class cannot be overridden, - make it as final.

  2. Make all the fields as private and final.

  3. Dont provide any setters or any method which changes the instance variable.

  4. Defensively copying the objects between callee and caller.

    Consider this tutorial for more