Immutable Class - Java
- Class should be made final - avoiding overriding of methods by sub classes
- All fields should be final and private - avoiding fields access outside the class and avoiding the changes in the field values
- No setters
- Make sure that mutable fields getters will return a defensive copy from their getter method, there by avoiding the state to be mutated
public final class Immutable {
private final Integer immutableinteger;
private final String immutableString;
private final Date mutableDate;
public Immutable(Integer immutableinteger, String immutableString, Date mutableDate) {
this.immutableinteger = immutableinteger;
this.immutableString = immutableString;
this.mutableDate = mutableDate;
}
public Integer getImmutableinteger() {
return immutableinteger;
}
public String getImmutableString() {
return immutableString;
}
public Date getMutableDate() {
return new Date(mutableDate.getTime());
}
}
public class ImmutableDemo {
public static void main(String[] args) {
Immutable immutable1 = new Immutable(100,"First String",new Date());
System.out.println(immutable1.getImmutableinteger()+ " " + immutable1.getImmutableString()+ " " + immutable1.getMutableDate());
modifyImmutable(immutable1.getImmutableinteger(),immutable1.getImmutableString(),immutable1.getMutableDate());
System.out.println(immutable1.getImmutableinteger()+ " " + immutable1.getImmutableString()+ " " + immutable1.getMutableDate());
Immutable immutable2 = new Immutable(200,"Second String",new Date());
System.out.println(immutable2.getImmutableinteger()+ " " + immutable2.getImmutableString()+ " " + immutable2.getMutableDate());
}
private static void modifyImmutable(Integer immutableInteger, String immutableString, Date mutableDate) {
immutableInteger = 1000;
immutableString = "ModifiedString";
mutableDate.setTime(11111);
}
}
Output:
100 First String Mon Jun 16 18:31:10 IST 2014
100 First String Mon Jun 16 18:31:10 IST 2014
200 Second String Mon Jun 16 18:31:10 IST 2014
Comments
Post a Comment