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.
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 :
You need to make sure that the class cannot be overridden, - make it as final.
Make all the fields as private and final.
Dont provide any setters or any method which changes the instance variable.
Defensively copying the objects between callee and caller.
Consider this tutorial for more
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With