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 ]
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.