How can we create an immutable class?

Showing Answers 1 - 1 of 1 Answers

sbarik

  • Jun 20th, 2006
 

Make a class immutable by following these guidelines :

  • always construct an object completely, instead of using a no-argument constructor combined with subsequent calls to setXXX methods
  • 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
  • ensure no methods can be overridden - make the class final, or use static factories and keep constructors private
  • make fields final
  • if the state of a mutable object field is "owned" by the native class, and the intention is to allow direct access to the field only from within that native class, then, when the field "crosses the border" (as in a get or set method, or in the constructor itself), then a defensive copy must be made, in order to maintain encapsulation.
  • if the state of a mutable object field is not "owned" by the native class, then a defensive copy of the object field is not necessary

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions