Senior
Tell us about immutable objects in Java — why are they needed, how to create them?
sobes.tech AI
Answer from AI
Immutable objects in Java are objects whose state cannot be changed after creation. They are important for ensuring thread safety, simplifying debugging, and preventing errors related to state modification.
To create an immutable object, you should:
- Make the class final so it cannot be subclassed and behavior cannot be changed.
- Make all fields private and final.
- Do not provide setters.
- Initialize all fields through the constructor.
- If fields are references to mutable objects, create copies when passing and returning them (to protect against external modifications).
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, making it safe for use in multithreaded environments.