Immutability.
A Java object is considered to be immutable when its state (properties and contents) cannot change after it is created.
Use of immutable objects is widely accepted as a sound strategy for creating simple, reliable code. Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state. java.lang.String and java.lang.Integer classes are the Examples of immutable
Immutable objects are simple to use test and construct.
Immutable objects are thread-safe by default.
Immutable objects are good Map keys and Set elements (Since state of these objects must not change while stored in a collection). This is the reason most of the times we prefer String objects as Key in many Map Collection objects.
Immutable objects do not require an implementation of clone.
Immutable objects allow hashCode to use lazy initialization, and to cache its return value.
To create a object immutable
Need to make the class final and all its member final so that once objects gets crated no one can modify its state.
Or
By making member as non final but private and not modifying them except in constructor. Also its NOT necessary to have all the properties final since you can achieve same functionality by making member as non final but private and not modifying them except in constructor.
A Java object is considered to be immutable when its state (properties and contents) cannot change after it is created.
Use of immutable objects is widely accepted as a sound strategy for creating simple, reliable code. Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state. java.lang.String and java.lang.Integer classes are the Examples of immutable
Immutable objects are simple to use test and construct.
Immutable objects are thread-safe by default.
Immutable objects are good Map keys and Set elements (Since state of these objects must not change while stored in a collection). This is the reason most of the times we prefer String objects as Key in many Map Collection objects.
Immutable objects do not require an implementation of clone.
Immutable objects allow hashCode to use lazy initialization, and to cache its return value.
To create a object immutable
Need to make the class final and all its member final so that once objects gets crated no one can modify its state.
Or
By making member as non final but private and not modifying them except in constructor. Also its NOT necessary to have all the properties final since you can achieve same functionality by making member as non final but private and not modifying them except in constructor.
Comments
Post a Comment