Junior — Middle
Can you name classes whose objects cannot be modified after creation?
sobes.tech AI
Answer from AI
In Java, objects that cannot be changed after creation are called immutable. Examples of classes with such objects include:
String— once a string is created, its content cannot be changed.- Wrapper classes for primitives:
Integer,Long,Double,Boolean, etc. java.time.LocalDate,LocalDateTime, and other classes from thejava.timepackage.
To make a class immutable, typically:
- All fields are declared as
final. - The class is declared as
final, or constructors and methods do not allow inheritance or state modification. - There are no setters, and all fields are initialized in the constructor.
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; }
}