An immutable object is an object which state is guaranteed to stay identical over its entire lifetime. This is really a good definition. Isn’t it? It means that the state of object once initialized, can never be changed anyhow.
Normally immutability in java is achieved through following steps :
- Don’t provide mutator methods for any field
- Make all fields final and private
- Don’t allow subclasses by declaring the class final itself
- Return deep cloned objects with copied content for all mutable fields in class
Please note that while it is possible to implement immutability without "final" keyword, its use makes that purpose explicit, to the human (the software developer) and the machine (the compiler).
Java also has its share of immutable classes which are primarily String class and wrapper classes. In this post, we will understand the need of immutability for String class.