Immutability is a software design principle that states that an object should not be able to be modified once it's been created. Enforcing immutability can help prevent bugs and ensure that data is not corrupted.
In Java, constants are often used in conjunction with the final keyword to enforce immutability. For example, consider the following class:
public final class ImmutableClass {private final int value;public ImmutableClass(int value) {this.value = value;}public int getValue() {return value;}// other methods ommitted for brevity}
As we can see, the ImmutableClass
class has a private field named value
that is declared as final
. This means that the value
of this field cannot be changed once it has been set. The only way to set the value of this field is through the constructor.
Enforcing immutability this way helps prevent the accidental modification of data and can make it easier to reason about the code. It can also make it easier to write thread-safe code, since immutable objects can be safely shared between threads without the need for any synchronization.
Immutable objects are often used as keys in HashMaps or as elements in sets. This is because they can be safely compared for equality without the need for any synchronization.
While an immutable object cannot be modified, it's possible for mutable objects to be contained within it. For example, consider the following class:
public final class ImmutableClass {private final List<String> values;public ImmutableClass(List<String> values) {this.values = Collections.unmodifiableList(values);}public List<String> getValues() {return values;}// other methods ommitted for brevity}
As we can see, the ImmutableClass
class contains a mutable object (a list of strings) but is wrapped in an unmodifiableList()
call from the Collections
class. This means that the list cannot be modified once it has been set.
The getValues()
method returns a reference to the list, but because it is unmodifiable, any attempt to modify it will result in an exception being thrown.
While this is just an example, it illustrates how we can use immutability to protect the state of an object while still allowing for mutable objects to be contained within it.