Immutable
- Immutable class’s state doesn’t change after initialization.
- Class is set as
final - Field variables are set as
finaland private- Cannot update the field variable’s value
- No setter methods
- No methods can update the values
- Getter method does not return the field variable reference
- If getter method returns a reference for the object, it can be updated from other places.
- Class is set as
- Immutable methods do not need
synchronizedkeyword added.- No synchronized keyword means it’s faster

{ frozen }: Instance field value doesn’t change after initialized- In Java,
finalkeyword supports that
- In Java,
{ concurrent }: It is safe to be ran from multiple threads at the same time- No need to add
synchronizedkeyword to the method as the method doesn’t change the state of shared resources.
- No need to add
Example

- Person class is immutable
- As the class is declared as
finalclass, we cannot create a subclass that inherits Person class.- This prevents from field values being updated from subclasses.
- As the field values on Person class is declared as
finalandprivate, it can only be set from constructor. (No setters)- If it is not private, the subclass would be able to update the value, which breaks immutable pattern.
- As the class is declared as

String vs StringBuffer
- String is immutable class while StringBuffer is a mutable class
final keyword
final Class
- Can not create subclass of
finalclass. - As we we cannot create a subclass of the
finalclass, the methods cannot be overriden as well.
final Method
- Cannot override
finalmethod.
final Field
- Can be initialized only once.
- Using constructor
- From declaration
Others
finallocal variable can be initialized only oncefinalmethod parameter can not be updated because it will be set from the invocation part.

Leave a comment