Senior
What is an immutable class? What are its disadvantages?
sobes.tech AI
Answer from AI
Immutable class is a class whose instances cannot be changed after creation. All fields are usually declared as final and initialized in the constructor.
Advantages:
- Thread safety without additional synchronization.
- Simplicity of understanding and debugging.
- Used as keys in collections.
Disadvantages:
- When modifying an object, a new instance must be created, which can lead to increased memory usage and reduced performance.
- Not always convenient for objects with many fields or complex hierarchy.
Example of an immutable class in Java:
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; }
}