Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to make a class immutable

 
Anu satya
Ranch Hand
Posts: 146
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
I had been to one interview. There was a question for which i had no answer.....

how to make a class immutable?

so, i answered...... just putting final before the class name will make the class immutable... i am not sure whether it is right or wrong...

can anyone please help me.....
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No.

The class should be final.
All its fields should be final.
All mutable reference type fields should return defensive copies in their get methods.
No set methods (they wouldn't compile anyway).
No need for a clone() method

And there is bound to be something I have forgotten.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The problem with lists of rules like this is that there are always exceptions. Note that the most famous immutable class of all -- String -- has a non-final member whose value changes sometime after the String is created. It's used to cache the hashCode after computing it once.

Making a class immutable means making sure that its user-visible state never changes. For example, the return values of its methods, given the same arguments, will generally be constant, so you want to make sure that no code outside the class can affect that. The rules Campbell gives are all good ideas to get you to that goal, but it's more important to understand what you're trying to accomplish and why.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic