• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

immutable classes

 
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
how can we write our own wrapper classes (immutable classes)?
 
Author and all-around good cowpoke
Posts: 13078
6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
Ranch Hand
Posts: 2937
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
reply
    Bookmark Topic Watch Topic
  • New Topic