Junior — Middle
What does immutability of objects mean and what are its advantages and disadvantages?
sobes.tech AI
Answer from AI
Objects are immutable if, after creation, their state cannot be changed — all their fields remain constant.
Advantages:
- Thread safety: immutable objects can be used safely in multithreaded environments without synchronization.
- Simplicity: fixed state reduces errors.
- Caching and reuse: immutable objects can be safely stored and transferred.
Disadvantages:
- Performance: changing an object requires creating a new one, which can lead to additional memory and time costs.
- Flexibility: not always convenient, especially if the object needs to be changed frequently.
In Java, immutable objects are usually created using:
finalfields- no setters
- initializing all fields via constructor
Example:
public final class Person {
private final String name;
private final int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() { return name; }
public int getAge() { return age; }
}
Such an object cannot be changed after creation.