Making a class immutable means that its state cannot be changed once it’s created. In other words, all the fields of the class are set at the time of instantiation and cannot be modified afterward. This can be achieved by using the following techniques:
- Declaring all fields as final: This ensures that the fields cannot be reassigned after they are initialized in the constructor.
- Making the class final: This prevents the class from being subclassed, which would allow for modification of its behavior or state.
- Providing no setter methods: By not providing any methods that modify the state of the class, it ensures that the class’s state cannot be changed after creation.
- Making mutable fields private: If the class contains mutable fields, they should be declared as private so that they cannot be accessed or modified from outside the class.