Immutable class is a class which once created , its content cannot be changed.Immutable Object are the objects whose state cannot be changed once constructed. e.g. String.
All wrapper class in java.lang are immutable - String, Integer, Boolean, Character, Byte, Short, Long, Float, Double, BigDecimal, BigInteger
Since the state of immutable object can not be changed once they are created, they are automatically thread safe/synchronized.
In order to create an immutable class, following steps should be followed
All wrapper class in java.lang are immutable - String, Integer, Boolean, Character, Byte, Short, Long, Float, Double, BigDecimal, BigInteger
Since the state of immutable object can not be changed once they are created, they are automatically thread safe/synchronized.
In order to create an immutable class, following steps should be followed
- Create a final class - no other class can not inherit immutable
- Set the values of properties using constructor only.
- Make the properties of the class final and private.
- Do not provide any setters for these properties.
- If the instance fields include reference variable to mutable object, don't allow those object to be changed.
E.g.
public final class MyImmutableClass{
private final String name;
private final int age;
private final Date mutableField;
public MyImmutableClass(final String name, final int age; Date mutableField){
super();
this.name = name;
this.age = age;
this.mutableField = mutableField;
}
public int getAge(){
return age;
}
public String getName(){
return name;
}
public Date getMutableField() {
return new Date(mutableField.getTime());
}
public String toString() {
return name +" - "+ age +" - "+ mutableField ;
}
}