Junior — Middle
Can you explain what an immutable class in Java is and how it is created?
sobes.tech AI
Answer from AI
An immutable class in Java is a class whose objects cannot be changed after creation. Such classes are useful for ensuring data security and multithreading.
To create an immutable class, you need to:
- Make the class
finalso it cannot be inherited and its behavior cannot be changed. - Make all fields
privateandfinal. - Do not provide setters (methods to modify fields).
- Initialize all fields through the constructor.
- If fields are mutable objects, return their copies in getters to avoid changing internal state.
Example:
public final class ImmutablePerson {
private final String name;
private final int age;
public ImmutablePerson(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}