Can anyone explain me on a simple example the difference between mutable and immutable objects in java?
Asked
Active
Viewed 2,098 times
-1
-
1I'm sure there're are many resources available. This [SO](http://stackoverflow.com/questions/279507/what-is-meant-by-immutable) could be helpful. – Kulasangar Dec 28 '16 at 11:04
-
9Here's a good link about the subject: http://stackoverflow.com/questions/214714/mutable-vs-immutable-objects – barreira Dec 28 '16 at 11:05
1 Answers
2
Mutable objects are objects whose state can be changed.
A state in Java is implemented with data fields.
An example of mutable object:
class Counter {
private int i = 0;
public void increase() {
i++;
}
}
So i
represents an internal state of the class Counter
here. And it can be changed as time goes by:
Counter counter = new Counter();
counter.increase(); // somewhere in the code
On the other hand, Immutable objects are objects whose state can't be changed once the object is created/initialized.
These objects should not have 'mutators' - setters, or in general methods that change an internal state.
Here is an example of an immutable object:
public final class Person {
private final String name;
private final int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return this.name;
}
public int getAge() {
return this.age;
}
}
As you see - although this class maintains the state (in fields name
and age
), it's impossible to change this state after the object is created (the constructor is called).

halfer
- 19,824
- 17
- 99
- 186

Mark Bramnik
- 39,963
- 4
- 57
- 97
-
1To make Person really immutable you should also make the class `final`, to prevent malicious/stupid users from extending it and adding mutable data/behaviour or overriding one of the existing methods to make them mutate the underlying object. – sisyphus Dec 28 '16 at 11:55
-