aspose file tools
The moose likes Java in General and the fly likes how to write our own immutable class like String. Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "how to write our own immutable class like String." Watch "how to write our own immutable class like String." New topic
Author

how to write our own immutable class like String.

A Babu
Ranch Hand

Joined: Nov 28, 2005
Posts: 114
hi,
how to write our own immutable class like String.guide me.

thanks in advance.

cheers,
babu.


Thanks,
www.Admakr.in
Jeff Albertson
Ranch Hand

Joined: Sep 16, 2005
Posts: 1780

1. Immutable classes are often final to prevent others from subclassing and playing games with the type.

2. Note there are no setters.

3. Immutable class often, but not always, define value types, which means they should have a useful equals method (and hashCode).

4. What if your class has many properties -- too many to pass to a constructor? Consider using the builder design pattern.


There is no emoticon for what I am feeling!
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
The definition of "immutable" is somewhat contrived among a majority of the Java community. The simple answer is "ensure that all of your operations are 'pure' - meaning consistent across infinite invocations". Some languages provide the ability to prove consistency, however, Java puts this onus on the developer.

As an example, create yourself a String instance, then set yourself the mission of invoking some operation on your instance where a different value is returned (given the same parameters) - you'll find that you cannot do it, therefore, the String contract is pure and consistent across infinite invocations - therefore, it is immutable.


Tony Morris
Java Q&A (FAQ, Trivia)
Jeff Albertson
Ranch Hand

Joined: Sep 16, 2005
Posts: 1780
That reminds me: my five-year old daughter asked me this riddle:

Q: What number comes after infinity?
A: And beyond!
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: how to write our own immutable class like String.
 
Similar Threads
Java
immutable classes
Creating our own String class?
How to make class immutable ?
own immutable class