This article shows how to create immutable classes in Java, using suitable examples, for a better explanation.
Immutable class in Java
Immutable classes are those classes whose object's state cannot be changed, once created. Any modification results in a new immutable object.
To better understand, let's use a simple example of String and StringBuffer classes. In other words using a substring, concat, and so on, results in a new immutable object, when an operation is performed on the StringBuffer class but does not create a new immutable object. Instead, it reflects the changes in the existing object only. Even JDK itself contains a number of immutable classes, like String, Float, and other wrapper classes. We can also create an immutable class by creating a final class that has final data members.
Guidelines for making an immutable class in Java
The following are simple guidelines that can be followed to make a class immutable in Java:
Example of making a class immutable by creating a final class
In the example given below, we create a final class named Student. There is only one final data member, a constructor, and a getter method.