This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to make a class immutable

 
Anu satya
Ranch Hand
Posts: 146
  • 0
  • 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
Pie
Posts: 47244
52
  • 0
  • 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: 24204
34
Chrome Eclipse IDE Mac OS X
  • 0
  • 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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic