• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Immutable classes

 
Juva Yuva
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 231
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is a good link that i bumped into.
 
Juva Yuva
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic