wood burning stoves 2.0*
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How to make a class immutable" Watch "How to make a class immutable" New topic
Author

How to make a class immutable

Anu satya
Ranch Hand

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


With Regards,
Anu
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37874
    
  22
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

Joined: Jul 08, 2003
Posts: 24183
    
  34

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 agree. Here's the link: http://aspose.com/file-tools
 
subject: How to make a class immutable
 
Similar Threads
Java
immutable
How to make a class immutable??????????
class Immutable
Making an existing class immutable