Junior — Middle
Can you explain what the term 'immutable object' means and what its key features are?
sobes.tech AI
Answer from AI
An immutable object is an object whose state cannot be changed after creation.
Key features:
- All fields of the object are declared as final and are initialized only in the constructor.
- There are no methods that modify the internal state of the object (no setters).
- If the object contains references to mutable objects, they are copied upon creation (deep copying) or copies are returned to prevent modification of the internal state.
Advantages:
- Thread safety without additional synchronization.
- Simplicity of understanding and debugging.
Example of an immutable class in Java:
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;
}
}
After creating a Person object, its name and age cannot be changed.