Create Own Immutable Class in Java
Creating an immutable class in Java involves several steps to ensure that once an instance of the class is created, it cannot be modified. Let’s create an immutable Student
class as an example.
Steps to Make a Class Immutable
- Make the class
final
: This prevents subclasses from altering its behavior. - Make fields
private
andfinal
: This ensures that fields cannot be modified after the object is constructed. - Provide only getters: No setters should be provided, so fields cannot be changed.
- Initialize all fields through the constructor: All fields should be assigned a value in the constructor.
- Perform deep copies for mutable objects: If the class has fields that refer to mutable objects, ensure they cannot be modified externally by returning a copy in the getter.
Here’s how to implement an immutable Student
class in Java:
public final class Student {
// Private final fields
private final int id;
private final String name;
private final int age;
// Constructor to initialize all fields
public Student(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
// Getters for each field
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
// Optional: Override toString for readable representation
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
Explanation
final
class: TheStudent
class is marked asfinal
so that no subclasses can alter its behavior or state.final
fields: The fieldsid
,name
, andage
are declaredfinal
, so they must be assigned only once and cannot be modified afterward.- No setters: We only provide
get
methods. No methods modify the internal state of the object. - Constructor assignment: All fields are assigned in the constructor, so there’s no way to change them afterward.
Usage Example
public class Main {
public static void main(String[] args) {
Student student = new Student(1, "Alice", 20);
System.out.println(student); // Output: Student{id=1, name='Alice', age=20}
// student.setName("Bob"); // Not allowed, no setter methods provided
}
}
OR
By Providing a modifier method:
public class Student {
private String name;
Student(String name) {
this.name = name;
}
public Student modify(String name) {
if (this.name.equals(name)) {
return this;
} else {
return new Student(name);
}
}
}
public class Main{
public static void main(String[] args){
Student student = new Student("Rajesh");
System.out.println(student);
student = student.modify("Rajesh");
System.out.println(student);
student = student.modify("Pramod");
System.out.println(student);
}
}
Output:
Student@3a5e8724
Student@3a5e8724
Student@1fbdfd2c