Senior
What is an immutable object and how to create it?
sobes.tech AI
Answer from AI
An immutable object is an object whose state cannot be changed after creation. In Java, this is important for thread safety and predictability.
To create an immutable class:
- Make the class
finalso it cannot be subclassed and behavior cannot be changed. - All fields should be
privateandfinal. - Do not provide setters.
- Initialize all fields through the constructor.
- If fields are objects, ensure they are also immutable or make deep copies when passing and returning.
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;
}
}