• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

immutable classes

 
eswar kumar
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
how can we write our own wrapper classes (immutable classes)?
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13071
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Look at the source code for the existing wrappers - for example java.lang.Float class declaration:

Note the use of final.
Now look at where the value is stored:

Note the use of private.
Etc. - just understand and follow the usage in the existing wrapper classes.
Bill
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Java wrapper classes are strongly immutable. You can also create weakly immutable classes by not declaring the class final and declaring all the public methods final. In that manner you can add behavior to the immutable class without breaking immutability. There are several things you must keep in mind when creating immutable classes, for example if part of the immutable state is an object reference you must not return that reference in a method but instead clone the object and return a reference to the clone. There was an excellent article here on JavaRanch a year or so ago about immutability, I'll try to locate that link. But as William said the best place to look is at the source code for String, Float, Integer, etc in the java.lang package.
[ November 29, 2003: Message edited by: Michael Morris ]
 
John Smith
Ranch Hand
Posts: 2937
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There was an excellent article here on JavaRanch a year or so ago about immutability, I'll try to locate that link.
You probably meant this article by David O'Meara
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic