Junior — Middle
Milliseid põhimõtteid tuleks kasutada Java klassi loomisel, et muuta see muutumatuks?
sobes.tech AI
Vastus AI-lt
To make a class in Java immutable, several principles must be followed:
- Declare the class as
final— so that it cannot be subclassed, which could alter its behavior. - Make all fields
privateandfinal— so that they cannot be changed after initialization. - Do not provide setters (methods to modify fields).
- Initialize all fields through the constructor.
- If fields are references to mutable objects (e.g., arrays, collections), create copies of them during assignment and when returning from getters, so external changes do not affect internal state.
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;
}
}
Such a class, after creating an object, does not allow changing its state, which is useful for thread safety and predictable behavior.