Item 13 Favor Immutability from Effective Java Edition #1
Joined: Apr 09, 2008
I have a doubt on the item#13 from Effective Java book (by Bloch), 1st para Pg70.
One caveat should be added concerning serializability. If you choose to have immutable class implement Serializable and it contains one or more fields that refer to mutable objects, you must provide an explicit readObject or readResolve method,..... (and so on)
I did not get how can an immutable object hold reference of mutable objects? Why would we still say a class is immutable even though it is holding a reference of mutable class?
The mutable object can exist as a final variable, never be changed by the class, and the reference never escape the containing Immutable class. For example, let's say I have a Person with a Date birthday field:
Now, a Date Object is Mutable, I can setTime() on it to change its values. But because the Date Object that is part of the Person's state never exists outside the Person instance, and Person instance itself can never change its value, then Person remains immutable, even if one of its fields is not.
Joined: Mar 05, 2008
Adding to that: Bloch's definition of "immutable" allows for mutable components - but it requires that access to any mutable components be restricted, such that clients of the class cannot obtain references to these mutable components. See rule 5 under Item 13: "Ensure exclusive access to any mutable components." That's why Steve's getBirthday() method returns a copy rather than the original Date object. No one outside this class can possibly obtain a reference to that original Date object.