Junior — Middle
What methods ensure the security and immutability of an object made according to the immutable principle?
sobes.tech AI
Answer from AI
To ensure the security and immutability of an object made according to the immutable principle, the following methods are used:
- Use of final fields — all fields of the object are declared as
finalso they cannot be changed after initialization. - Absence of setters — do not provide methods to change the state of the object after creation.
- Initialization through constructor — all values are set during object creation.
- Protection against modification of reference fields — if the object contains references to mutable objects, their copies (deep copy) should be created when passing and returning, so external code cannot change the internal state.
- Class declared as final — to prevent inheritance and overriding behavior that could violate immutability.
Example of a simple 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;
}
}
Thus, the object cannot be changed after creation, which ensures its safety and predictability.