How can we create immutable class?

An immutable class is created in such a way that its objects cannot be modified after they are instantiated. Once the object's state is initialized, it remains unchanged throughout its lifetime. This design improves thread safety, security, and reliability.

Key Points: • Declare the class as final to prevent inheritance and modification through subclasses. • Make all instance variables private and final so they can be assigned only once. • Initialize all fields through a constructor. • Do not provide setter methods that can modify the object's state. • If the class contains mutable objects, return defensive copies instead of direct references. • Immutable classes are naturally thread-safe because their state never changes.

Steps to Create an Immutable Class:

1. Declare the class as final. 2. Make all fields private and final. 3. Initialize fields using a constructor. 4. Do not provide setter methods. 5. Return field values through getter methods only. 6. Protect mutable fields by returning copies when necessary.

Example: The String class is a well-known immutable class. Once a String object is created, its value cannot be changed.

Code Example:

public final class Employee {

    private final String name;
    private final int id;

    public Employee(String name, int id) {
        this.name = name;
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public int getId() {
        return id;
    }
}

public class Demo {

    public static void main(String[] args) {

        Employee emp = new Employee("Amol", 101);

        System.out.println(emp.getName());
        System.out.println(emp.getId());
    }
}

Benefits of Immutable Classes:

• Thread-safe by design • Improved security • Easier debugging and maintenance • Prevents accidental data modification • Safe to use in concurrent applications

Interview Tip: A concise interview answer is:

"To create an immutable class, declare the class as final, make all fields private and final, initialize them through a constructor, avoid setter methods, and expose data only through getter methods. This ensures that the object's state cannot be changed after creation."