hi, how to write our own immutable class like String.guide me.
thanks in advance.
Joined: Sep 16, 2005
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!
Joined: Sep 24, 2003
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.