| Author |
How to make a class immutable (like String)?
|
Arjun Reddy
Ranch Hand
Joined: Nov 10, 2007
Posts: 624
|
|
Whenever we perform any operation on the class's objects, the old object remains and a new object is created. Can we do this? Thanks.
|
Be Humble... Be Nice.
|
 |
Darryl Burke
Bartender
Joined: May 03, 2008
Posts: 4202
|
|
-- If you don't write any mutators, the class is immutable. -- You can't "perform any operation" on the instance of an immutable class. -- Creating a new instance is up to you as the programmer. db
|
luck, db
There are no new questions, but there may be new answers.
|
 |
Paul Sturrock
Bartender
Joined: Apr 14, 2004
Posts: 10336
|
|
the old object remains and a new object is created
The string literal pool is not part of the immutable behaviour of a class. (Have a read of this). Immutable just means you can't change the value of something, it doesn't imply that such an object will be stored differently. The string literal pool is part of the JVM. You can't get objects of other types to use it. But you can (sort of) implement simmilar logic if you control access to the construction of a new instance of your object. Have a google for "factory patterns" and you'll get a lot of information on the subject. [ June 16, 2008: Message edited by: Paul Sturrock ]
|
JavaRanch FAQ HowToAskQuestionsOnJavaRanch
|
 |
Joanne Neal
Rancher
Joined: Aug 05, 2005
Posts: 3011
|
|
Originally posted by Arjun Reddy: Whenever we perform any operation on the class's objects, the old object remains and a new object is created. Can we do this? Thanks.
I may be wrong, but my interpretation of this is that the OP is thinking of methods such as substring which return a new String rather than modifying the existing one. If I'm right, then you can certainly do something similar in your own class. All you need to do in these methods is create a new instance of your class and then set the state of this new instance based on the state of the existing instance and the required modifications and then return a reference to this new instance.
|
Joanne
|
 |
 |
|
|
subject: How to make a class immutable (like String)?
|
|
|