wood burning stoves
The moose likes Beginning Java and the fly likes How to make a class immutable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How to make a class immutable" Watch "How to make a class immutable" New topic

How to make a class immutable

Anu satya
Ranch Hand

Joined: Mar 17, 2005
Posts: 146
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.....

With Regards,
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 43885

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

Joined: Jul 08, 2003
Posts: 24189

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.

[Jess in Action][AskingGoodQuestions]
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com
subject: How to make a class immutable
It's not a secret anymore!