xploreraj xploreraj - 26 days ago 21
Java Question

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

This is just from an academic learning point of view. All I know is that whenever we want to make some class immutable,
- it has to consist of final primitive fields
- reference does not escapes during construction of object
- if uses other objects, then those objects need to be recursively immutable too or API immutable classes like java.lang.String, among some other detailed lookouts!

But I recently came accross a question wherein an interviewer asked a candidate to create an immutable class that has a java.util.Date in it. My first impression tells that its not possible although we can do workarounds with String containing the date string rather than in Date object itself.

Please clarify me on this. Thank you.

Answer

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

Comments