Principal
What immutable objects do you know in Java?
sobes.tech AI
Answer from AI
In Java, immutable objects are objects whose state cannot be changed after creation. A classic example is the String class. Other well-known immutable objects:
- Wrappers for primitive types:
Integer,Long,Double,Boolean, etc. - Classes from the
java.timepackage (e.g.,LocalDate,LocalDateTime,Instant) that represent immutable dates and times.
To make a custom class immutable, you should:
- Make the class
finalor do not provide methods to modify the state. - All fields should be
private final. - Do not provide setters.
- If fields are references to mutable objects, create copies when passing and returning.
Example of a simple immutable class:
public final class Point {
private final int x;
private final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() { return x; }
public int getY() { return y; }
}