Immutability means that something cannot be changed. In Java, an immutable class is one whose state cannot be changed once it has been created.
This shot aims to give a guideline of how to make a class immutable – it contains an example of how to create an immutable class.
The complete code is available on Github.
The Java documentation does give a list of guidelines for creating an immutable class, but we will try to understand it better.
To make a class immutable, follow these steps:
Why do we need to complete all the steps above to make a class immutable?
Lets look at an example of an immutable class:
import java.util.Date;/*** Steps for making a class immutable:* 1. Declare the class as final* 2. Make all its fields final* 3. For all mutable fields, class should make a defensive copy and only return the copy to the calling code* 4. Do not provide any setter methods.*/public final class ImmutableClass {/*** Integer and String classes are immutable whereas Date class is mutable*/private final Integer immutableInteger;private final String immutableString;private final Date mutableDate;public ImmutableClass(Integer i, String s, Date d) {this.immutableInteger = i;this.immutableString = s;this.mutableDate = new Date(d.getTime());}public String getImmutableString() {return immutableString;}public Integer getImmutableInteger() {return immutableInteger;}public Date getMutableDate() {return new Date(mutableDate.getTime());}@Overridepublic String toString() {return immutableInteger + ", " + immutableString + ", " + mutableDate;}}
We have three fields in the class:
Integer
typeString
typeDate
type.The String
and Integer
classes are immutable, but the Date
class is mutable. Thus, we created a new Date object when assigning the Date to the class field.
That’s all for immutability!
Free Resources