File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Item 13 Favor Immutability from Effective Java Edition #1 Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Item 13 Favor Immutability from Effective Java Edition #1" Watch "Item 13 Favor Immutability from Effective Java Edition #1" New topic
Author

Item 13 Favor Immutability from Effective Java Edition #1

Piyush Porwal
Ranch Hand

Joined: Apr 09, 2008
Posts: 30
I have a doubt on the item#13 from Effective Java book (by Bloch), 1st para Pg70.
It says:
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?

-Piyush Porwal (Junk box)
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 3026
    
    4

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.


Steve
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 2770
    
    2
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.
 
I agree. Here's the link: jrebel
 
subject: Item 13 Favor Immutability from Effective Java Edition #1
 
Similar Threads
Why are Strings Immutable ?
Should Tuple2 be immutable?
Why String class is immutable
primitive data type manipulation in wrapper classes
General question about the String class - and final classes in general.