Junior — Middle
What approaches can ensure the immutability of objects in programming?
sobes.tech AI
Answer from AI
Objects in programming can be made immutable using the following methods:
-
Declare the class as
finalto prevent inheritance and behavior modification. -
Make all fields
private finalso they cannot be changed after initialization. -
Initialize all fields through the constructor, without setters.
-
Do not provide methods that modify the object's state (e.g., setters).
-
For reference fields to mutable objects (e.g., collections), use immutable versions or return copies.
Example of an 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;
}
}
Such an object cannot be changed after creation.