Immutable simply means unmodifiable or unchangeable. Immutable class means that once an object is created, we cannot change its content. In Java, all the wrapper classes (like String, Boolean, Byte, Short) and String class is immutable.
Why is even immutability introduced at first ?
An immutable object is one whose state cannot and will not change after it’s initial creation. Immutable objects are great, mostly because they are Thread safe (and threaded code should be avoided as much as possible). You can pass them around without fear they will be changed.
Since the internal state of an immutable object remains constant in time, we can share it safely among multiple threads.
We can also use it freely, and none of the objects referencing it will notice any difference, we can say that immutable objects are side-effects free.
How to make a class Immutable
Prerequisites to create an Immutable class:
- Class must be declared as final (So that child classes can’t be created)
- Data members in the class must be declared as final (So that we can’t change the value of it after object creation)
- A parameterized constructor
- Getter method for all the variables in it
- No setters(To not have option to change the value of the instance variable)
Examples of Immutable class :
final class EmployeeFinalClass {
private final String empName;
private final int empId;
public EmployeeFinalClass(String a, int b) {
this.empName = a;
this.empId = b;
}
public int getEmpId() {
return empId;
}
public String getEmpName() {
return empName;
}
}
class Test {
public static void main(String[] args) {
EmployeeFinalClass obj = new EmployeeFinalClass("Robin Hood", 1001);
System.out.println(obj.getEmpName());
System.out.println(obj.getEmpId());
// any modification to final class properties
// is not permitted, throws compilation error
// Wanna Test ? - uncomment below line to check.
//obj.empName="";
}
}
OUTPUT
Robin Hood
1001
Concept of Defensive copy
- If a field is a mutable object create defensive copies of it for getter methods.
- If a mutable object passed to the constructor must be assigned to a field, create a defensive copy of it.
Example to understand Defensive copy concept:
1.) Creating defensive copy of getter method
import java.util.Date;
public class ImmutablFieldObjectTest {
private final Date date;
public ImmutablFieldObjectTest() {
this.date = new Date();
}
public Date getDate() {
// return date;
return new Date(date.getTime());
}
public static void main(String[] args) {
ImmutablFieldObjectTest obj = new ImmutablFieldObjectTest();
System.out.println(obj.getDate());
obj.getDate().setTime(obj.getDate().getTime() + 1000);
// Now ImmutablFieldObjectTest date is not changed
// because we changed the copy,
// not the original date
System.out.println(obj.getDate());
}
}
OUTPUT
Mon Jul 29 21:13:41 IST 2019
Mon Jul 29 21:13:41 IST 2019
2.) Creating defensive copy of Object – if this object is to be assigned to another object.
import java.util.Date;
public class ImmutablFieldObjectTest {
private final Date date;
public ImmutablFieldObjectTest(Date date) {
this.date = new Date(date.getTime());
}
public Date getDate() {
// return date;
return new Date(date.getTime());
}
public static void main(String[] args) {
Date date = new Date();
ImmutablFieldObjectTest obj = new ImmutablFieldObjectTest(date);
System.out.println(obj.getDate());
date.setTime(date.getTime() + 1000);
// Now ImmutablFieldObjectTest date is not changed.
// We create a copy on the constructor
// so a change to the external date will not affect
// the internal state of
// ImmutablFieldObjectTest instance
System.out.println(obj.getDate());
}
}
OUTPUT
Mon Jul 29 22:27:43 IST 2019
Mon Jul 29 22:27:43 IST 2019
Immutable Objects given by java:
- File / String / Wrapper classes
- JDBC apis(Callable, statement, connections) : immutable object
- UseCases : Hashtable , adding string key
Summary
In this article we learnt about Immutable Class Concept in java and its importance. We also saw an example of Immutable class, learnt about concept of defensive copy of getter method and Object.
Hope you liked the article !