• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to make a class immutable (like String)?  RSS feed

 
Arjun Reddy
Ranch Hand
Posts: 629
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Darryl Burke
Bartender
Posts: 5167
11
Java Netbeans IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
-- 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
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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 ]
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!