What is Immutable Class In Java?
An immutable class in Java is a class whose instances cannot be modified once created. This means that all fields are final, and any method that would alter the state of the object returns a new instance instead. This design ensures thread safety and simplifies reasoning about code since objects cannot be changed unexpectedly. Common examples of immutable classes in Java include the String
class and the Integer
class. To create an immutable class, you typically provide a constructor to initialize fields and omit setter methods, ensuring encapsulation and preventing modifications.