Immutable Objects
Objects that never change.
Immutable Objects
Analogy: concept
Immutable Objects are like Diamonds:
Once formed, they cannot be changed. If you want a different shape, you have to cut a new diamond. You can't just mold the old one like clay.
The Shielded Vault
Try to modify the content of the Vault. Since it's immutable, you can't! You have to create a new one.
Immutable Objects (The Vault)
Vault Content
Gold Bars
Immutable
Waiting for action...
*To "change" an immutable object, you must create a NEW one.
Key Concepts
- Immutability: An object whose state cannot be modified after it is created.
- Benefits:
- Thread Safety: No need for locks because data never changes.
- Security: No one can secretly modify your data.
- Simplicity: Easier to understand and debug.
- Examples:
Stringin Java,tuplein Python.
The Code
How to make a class immutable in Java:
- Make the class
final(so no one can extend it). - Make all fields
privateandfinal. - Don't provide "Setters".
- Initialize everything in the Constructor.
final class ImmutablePoint {
private final int x;
private final int y;
public ImmutablePoint(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() { return x; }
public int getY() { return y; }
// No setX() or setY()!
}
Up Next
Generics