Junior — Middle
Which classes implement immutable objects in programming?
sobes.tech AI
Answer from AI
In Java, immutable objects are objects whose state cannot be changed after creation. Main classes implementing immutable objects:
- String — a class for strings, which cannot be changed after creation.
- Wrapper classes for primitives:
Integer,Long,Double,Boolean, etc. - BigInteger and BigDecimal — for working with large numbers and precise arithmetic.
- LocalDate, LocalDateTime, and other classes from the
java.timepackage.
To create your own immutable class, you need to:
- Make the class
finalor do not provide methods to change the state. - Make all fields
private final. - Do not provide setters.
- If fields are references to mutable objects, return their copies.
Example:
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; }
}