• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
  • Piet Souris
  • Frits Walraven
  • Carey Brown

Item 13 Favor Immutability from Effective Java Edition #1

Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
Posts: 4179
IntelliJ IDE Python Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
Posts: 3571
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
All of the world's problems can be solved in a garden - Geoff Lawton. Tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
    Bookmark Topic Watch Topic
  • New Topic