InterviewVault
Welcome back, Sujit Kumar Mishra
Admin
SK Mishra
Revision Mode
Document technical questions and best-practice answers.
How can you create a custom immutable class?
An immutable class is a class whose objects cannot be changed after creation. To make a class immutable in Java, follow these simple steps:
1: Make the class final so it cannot be subclassed.
2: Make all fields private and final so they cannot be changed after initialization.
3: Do not provide any setter methods.
4: Initialize all fields via the constructor.
5: If any field is an object, return a copy in the getter method (to prevent changes from outside).
Example:
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 you create a Person object, you cannot change its name or age, making it immutable.
Key points to remember:
1: Use final for class and fields.
2: Only getters, no setters.
3: All fields set in constructor.