Java – Mutable and Immutable Objects
This article shows you the difference between Mutable and Immutable objects in Java
1. Mutable object – You can change the states and fields after the object is created. For examples: StringBuilder
, java.util.Date
and etc.
2. Immutable object – You cannot change anything after the object is created. For examples: String
, boxed primitive objects like Integer
, Long
and etc.
1. Java Mutable Example
Normally, it provides a method to modify the field value, and the object can be extended.
MutableExample.java
package com.mkyong;
public class MutableExample {
private String name;
MutableClass(String name) {
this.name = name;
}
public String getName() {
return name;
}
// this setter can modify the name
public void setName(String name) {
this.name = name;
}
public static void main(String[] args) {
MutableExample obj = new MutableExample("mkyong");
System.out.println(obj.getName());
// update the name, this object is mutable
obj.setName("new mkyong");
System.out.println(obj.getName());
}
}
Output
mkyong
new mkyong
2. Java Immutable Example
To create an Immutable object, make the class final, and don’t provide any methods to modify the fields.
ImmutableExample.java
package com.mkyong;
// make this class final, no one can extend this class
public final class ImmutableExample {
private String name;
ImmutableExample (String name) {
this.name = name;
}
public String getName() {
return name;
}
//no setter
public static void main(String[] args) {
ImmutableExample obj = new ImmutableExample("mkyong");
System.out.println(obj.getName());
// there is no way to update the name after the object is created.
// obj.setName("new mkyong");
// System.out.println(obj.getName());
}
}
Output
mkyong
Note
Immutable object is simple, thread-safe (no need synchronization), less prone to error and more secure. If possible, make all objects immutable.
Immutable object is simple, thread-safe (no need synchronization), less prone to error and more secure. If possible, make all objects immutable.
P.S Please refer to the Effective Java Book – Item 15: Minimize mutability.
I’d like to suggest an edit.
In the MutableExample class, you have named the constructor – “MutableClass”, which should be “MutableExample” I believe, same as the class name.
super sir
the variable (i.e. name in class ImmutableExample ) must be final to make it immutable.
no setter is enough
I thing, Jagat is right.
Here in this example, you can update the value of the variable name.
obj. name = “Jagat”;
So the variable “name” must be made final.
It is not an exact example of the Immutable class construction, this example shows the use of Immutable