Junior — Middle
What methods can be used to implement immutability of objects in programming?
sobes.tech AI
Answer from AI
Objects immutability in programming can be achieved in several ways:
- Declaring fields as final — in Java, object fields are declared with the
finalmodifier to prevent them from being changed after initialization. - Absence of setters — not providing methods to modify the object's state after creation.
- Initializing all fields through the constructor — all values are set during object creation.
- Using immutable data types — for example,
String,Integer, and other classes from thejava.timepackage. - Deep copying mutable objects — if an object contains references to mutable objects, their copies should be created to prevent internal state changes.
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;
}
}
Such a class cannot be modified after creation, ensuring its immutability.