wood burning stoves 2.0*
The moose likes Java in General and the fly likes immutable classes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "immutable classes" Watch "immutable classes" New topic
Author

immutable classes

eswar kumar
Ranch Hand

Joined: Oct 20, 2002
Posts: 98
how can we write our own wrapper classes (immutable classes)?
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12769
    
    5
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

Joined: Jan 30, 2002
Posts: 3451
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 ]

Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher
John Smith
Ranch Hand

Joined: Oct 08, 2001
Posts: 2937
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: immutable classes