aspose file tools*
The moose likes Beginning Java and the fly likes Immutable classes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Immutable classes" Watch "Immutable classes" New topic
Author

Immutable classes

Juva Yuva
Greenhorn

Joined: Dec 18, 2008
Posts: 17
What are the basic steps to create Immutable classes ?

1) Declaring the class as final so as to avoid subclassing and overriding
2) Declaring the accessor methods for the instance variables
3) Making the instance variables private.

Is that all.Anything i missed ?
[ December 25, 2008: Message edited by: Juva Yuva ]
Harvinder Thakur
Ranch Hand

Joined: Jun 10, 2008
Posts: 231
Here is a good link that i bumped into.


thanks
Harvinder
Juva Yuva
Greenhorn

Joined: Dec 18, 2008
Posts: 17
Originally posted by Juva Yuva:
What are the basic steps to create Immutable classes ?

1) Declaring the class as final so as to avoid subclassing and overriding
2) Declaring the accessor methods for the instance variables
3) Making the instance variables private.

Is that all.Anything i missed ?

[ December 25, 2008: Message edited by: Juva Yuva ]


Thanks Harvinder.
Correcting my steps ( for other beginners to read)

1) Making all the instance variables final and private.
2) Declaring and implementing public accessor methods for the instance variables.
3) In the accessor method (get) , sending the copy of the instance variables by creating clone , so to avoid the reference being used outside to change the state of it.
4) Declaring the class as final so as to avoid subclassing and overriding (optional, so as to provide Mutable functionality by subclassing )
[ December 26, 2008: Message edited by: Juva Yuva ]
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39882
    
  28
You need to check the clone methods of all your fields carefully, that they will actually produce real copy variables. There is no need to clone or copy immutable classes.
It is quite important to make the class final, too.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Immutable classes