Junior — Middle
What are the advantages and disadvantages of using classes whose objects cannot be modified after creation?
sobes.tech AI
Answer from AI
Classes with immutable objects in Java have the following advantages and disadvantages:
Advantages:
- Thread safety: Immutable objects can be safely used in multithreaded environments without synchronization.
- Ease of understanding: The state of the object does not change after creation, simplifying debugging and code comprehension.
- Use as keys: Such objects can be used in collections where immutability is important (e.g., in
HashMap) without the risk of hash code changes. - Caching and optimization: Immutable objects are easier to cache and reuse.
Disadvantages:
- Performance: To modify an object, a new instance must be created, which can lead to additional memory and time costs.
- Flexibility: The inability to change the object's state after creation can complicate scenarios where mutability is required.
Example of an immutable class:
public 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; }
}