Junior — Middle
What approaches exist for creating immutable objects in object-oriented programming?
sobes.tech AI
Answer from AI
The following approaches are used to create immutable objects in object-oriented programming:
-
Using final classes and final fields (in Java) — the class is declared as final so it cannot be inherited, and fields are declared as final so they cannot be changed after initialization.
-
Absence of setters — do not provide methods to modify the object's state after creation.
-
Initializing all fields through the constructor — all values are set when the object is created.
-
Deep copying mutable objects — if an object contains references to mutable objects, their copies should be created so external changes do not affect the state.
Example of a simple immutable class in Java:
public final class ImmutablePoint {
private final int x;
private final int y;
public ImmutablePoint(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() { return x; }
public int getY() { return y; }
}
Such an object cannot be changed after creation.