Senior
Design an auto-tagging system for products by photo on a marketplace.
sobes.tech AI
Answer from AI
To create an immutable object in Java after initialization, you can use the following approaches:
- Declare the class as
finalso it cannot be subclassed and behavior cannot be overridden. - Make all fields
private finalso they cannot be changed after assignment. - Initialize all fields via the constructor.
- Do not provide setters (methods to modify fields).
- If fields are mutable objects (e.g., collections), return copies or use unmodifiable wrappers (e.g.,
Collections.unmodifiableList).
Example:
public final class ImmutablePerson {
private final String name;
private final int age;
public ImmutablePerson(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
If there are collections:
private final List<String> items;
public ImmutableClass(List<String> items) {
this.items = Collections.unmodifiableList(new ArrayList<>(items));
}
public List<String> getItems() {
return items;
}
Thus, the object cannot be changed after creation.