Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Making Immutable class

 
Prakash Rai
Ranch Hand
Posts: 106
Eclipse IDE MyEclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Q1. How to make StringBuffer class Immutable class.?
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Pie
Posts: 15438
41
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Campbell Ritchie
Sheriff
Pie
Posts: 49776
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 221
1
Eclipse IDE Java Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2969
59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 49776
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 221
1
Eclipse IDE Java Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, I meant tinkering with source code of one's own classes!
 
Campbell Ritchie
Sheriff
Pie
Posts: 49776
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You mean you want to create an immutable class which has nothing to do with StringBuilder?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic