Immutable classes are classes whose objects cannot be modified after they are created. Once an object is initialized, its state remains constant throughout its lifetime. Any change requires creating a new object rather than modifying the existing one.
Key Points: • The state of an immutable object cannot be changed after construction. • Immutable classes improve security, reliability, and thread safety. • Fields are typically declared as private and final. • Immutable classes do not provide setter methods. • Objects of immutable classes can be safely shared among multiple threads without synchronization. • The String class is one of the most common examples of an immutable class in Java.
Example: When a String value is modified, Java creates a new String object instead of changing the original object.
Code Example:
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());
}
}Characteristics of an Immutable Class:
• Class is often declared final • Fields are private and final • No setter methods • Values are initialized through the constructor • Object state cannot be modified after creation
Benefits of Immutable Classes:
• Thread-safe by default • Easier to maintain and debug • Improved security • Prevents accidental data modification • Safe to use as keys in collections such as HashMap
Interview Tip: A concise interview answer is:
"An immutable class is a class whose objects cannot be modified after creation. Its fields are initialized once, typically through a constructor, and no setter methods are provided. Immutable classes are thread-safe, secure, and easier to maintain."