Creating Immutable Class in java
Below are mandatory steps to create the immutable class in java
- Declare the class as final, no one will extend it.
- Make all properties/fields in the class as final and private, so there is no scope to modify the fields.
- Don’t provide “setter” methods, methods that modify fields or objects referred to by fields.
- Force to construct an object of the class directly, do not use any setter methods
Following is some sample code.
final class MyImmutableClass
{
private final String name;
private final int age;
private final String address;
public MyImmutableClass(String personName,int personAge,String personAdress) {
name = personName;
age = personAge;
address = personAdress;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getAddress() {
return address;
}
}
public class ImmutableTest {
public static void main(String[] args) {
MyImmutableClass immutable = new MyImmutableClass("Mike", 25, "Astralia");
}
}
Benefits of making a class immutable
- Immutable objects are automatically thread-safe.
- Once created the state of the immutable object cannot be changed so there is no chance to get them into an inconsistent state.
- The references to the immutable objects can be easily shared or cached without having to copy or clone them as there state cannot be changed ever after construction.
- Most important point is we can use immutable objects is as the keys of a map.
Below are Default immutable classes in java
- All wrapper classes
String, Integer, Boolean, Character, Byte, Short, Long, Float, Double