• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to make a class immutuable in Java?  RSS feed

 
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How to make a class immutuable in Java?
 
Saloon Keeper
Posts: 4036
94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
By not providing a way to alter it after creation: keep fields private, and don't allow methods to change any fields.
 
Bartender
Posts: 11445
18
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Make a class immutable by following these guidelines :

ensure the class cannot be overridden - make the class final, or use static factories and keep constructors private
make fields private and final
force callers to construct an object completely in a single step, instead of using a no-argument constructor combined with subsequent calls to setXXX methods (that is, avoid the Java Beans convention)
do not provide any methods which can change the state of the object in any way - not just setXXX methods, but any method which can change state
if the class has any mutable object fields, then they must be defensively copied when passed between the class and its caller
For more details refer this link

http://www.javapractices.com/topic/TopicAction.do?Id=29


Thanks,
Athira
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!