Junior — Middle
Could you give an example of a class that is immutable after creation?
sobes.tech AI
Answer from AI
An example of an immutable class in Java is the String class. To create your own immutable class, you need to:
- Make the class
finalso it cannot be subclassed and its behavior cannot be changed. - Make all fields
private final. - Initialize all fields through the constructor.
- Do not provide setters.
- If the fields are objects, ensure their immutability or return copies.
Example of a simple immutable class:
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;
}
}
Once a Person object is created, its state cannot be changed.