简体   繁体   中英

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.

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

1) Don't provide “setter” methods.

2) Make all fields final and private

3) Don't allow subclasses to override methods - Declare class as final

4) For mutable instance variables - Ex date: In this case a special attention to be given.

5) Make the constructor private and construct instances in factory methods. Factory method to store object creation logic in single place.

   public static MyImmutableClass createNewInstance(Integer fld1, String fld2, Date date)
{
    return new MyImmutableClass (fld1, fld2, date);
}

6) Instead a new Date object, with content copied to it, should be returned.

public Date getDateField() {
    return new Date(dateField.getTime());
}

- Here dateField is field which is set inside private constructor

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM