Wednesday, January 16, 2008

Making an object Immutable.

Definition: Immutable objects are those whose state(i.e object data) cannot change once the object has been constructed.

Making an object immutable:

1. Make the class final
2. Make the constructor parameterized, so that we need not allow setter methods
3. Make all fields final and private
4. Provide getter methods for retrieving values of fields.

Example:

public final class XYZ{

private final String name;

//constructor
public XYZ(String paramName){
name=paramName;

}

//getter method
public String getName(){
return name;

}

}

Important: Note that javadoc 1.4 includes the -tag option, whereby simple custom tags may be defined. One might define an @is.Immutable tag, for example, to document a class as being immutable

No comments: