File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Immutable Class" Watch "Immutable Class" New topic
Author

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
Sheriff

Joined: Oct 27, 2005
Posts: 19718
    
  20

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


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
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
Sheriff

Joined: Oct 13, 2005
Posts: 39395
    
  28
Fields should usually be private anyway, so you would want private and final for an immutable class.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Immutable Class