Here are some guidelines i found on internet to make Java class immutable and also i am writing example here.
- 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
/**
* @author Dinesh Sonsale
* @eMail sonsale@gmail.com
* Class is final
*/
public final class Immutable {
/*Field is private and final with not setter method */
private final String myName;
/* Parameterized constructor to set all final variables */
public Immutable(String myName){
this.myName = myName;
}
public String getMyName() {
return myName;
}
}
Comments
Post a Comment