Meaningless Drivel is fun!*
The moose likes Java in General and the fly likes Making  Immutable class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Making  Immutable class " Watch "Making  Immutable class " New topic
Author

Making Immutable class

Prakash Rai
Ranch Hand

Joined: Jan 10, 2011
Posts: 101

Q1. How to make StringBuffer class Immutable class.?
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 13875
    
  10

You cannot make StringBuffer immutable. In fact, you cannot make any class immutable without modifying the source code of the class - and since StringBuffer is a class in the standard Java library, you can't modify its source code.

Here's a good article on immutable classes: Java theory and practice: To mutate or not to mutate?


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36514
    
  16
You ought usually to use StringBuilder rather than StringBuffer.
Both classes are specially designed to be easily mutable. They are counterparts to the String class, which is designed to be immutable. So you ought not even to try making a mutable StringBuilder.
Rajdeep Biswas
Ranch Hand

Joined: Mar 26, 2012
Posts: 186

I think we have to modify the source code such that it prevents resetting the instance or changing the object state (like one without any setter and some other things)...
Tony Docherty
Bartender

Joined: Aug 07, 2007
Posts: 1945
    
  28
Rajdeep Biswas wrote:I think we have to modify the source code such that it prevents resetting the instance or changing the object state

As Campbell has already said, the whole point of the StringBuffer and StringBuilder classes is that they are mutable, if you want an immutable version then just use a String class.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36514
    
  16
Those classes were written as mutable classes because String is immutable. Anyway, you can’t alter the source code because the compiler won’t compile anything claiming to be in the java.lang package. And close examination of the documentation will reveal something else about StringBuilder.
Rajdeep Biswas
Ranch Hand

Joined: Mar 26, 2012
Posts: 186

Yes, I meant tinkering with source code of one's own classes!
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36514
    
  16
You mean you want to create an immutable class which has nothing to do with StringBuilder?
 
wood burning stoves
 
subject: Making Immutable class
 
Similar Threads
Java
equals() and ==
How to make a class immutable??????????
Is the Math class considered immutable?
Math class immutable