File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Immutable Class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Immutable Class" Watch "Immutable Class" New topic

Immutable Class

jose chiramal
Ranch Hand

Joined: Feb 12, 2010
Posts: 266
The following have to be followed for creating an Immutable class:

• Make all fields private
• Don't provide mutators
• Ensure that methods can't be overridden by either making the class final (Strong Immutability) or making your methods final (Weak Immutability)
• If a field isn't primitive or immutable, make a deep clone on the way in and the way out. (I did not understand this point, can someone please clarify this ?)
Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

An example with Date

"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
Rob Spoor

Joined: Oct 27, 2005
Posts: 20273

The solution of course is to make copies both in the constructor and in the getter method:

How To Ask Questions How To Answer Questions
jose chiramal
Ranch Hand

Joined: Feb 12, 2010
Posts: 266
All fileds should be private or private final ??

Since immutable means something that cannot be changed ?

Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46349
Fields should usually be private anyway, so you would want private and final for an immutable class.
I agree. Here's the link:
subject: Immutable Class
It's not a secret anymore!