Thursday, November 29, 2012

Immutable objects

Immutable objects
Immutable objects are objects whose state cannot change after construction. Examples of immutable objects from the JDK include String and Integer. (String methods, such as String.replace do not change the instance, but create new Strings)

Requirements for immutable classes:
•    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 setter methods
•    do not provide any methods which can change the state of the object in any way;

No comments:

Post a Comment