Can anyone explain me on a simple example the difference between mutable and immutable objects in java?
-
1I'm sure there're are many resources available. This SO could be helpful.Kulasangar– Kulasangar2016-12-28 11:04:45 +00:00Commented Dec 28, 2016 at 11:04
-
9Here's a good link about the subject: stackoverflow.com/questions/214714/mutable-vs-immutable-objectsbarreira– barreira2016-12-28 11:05:58 +00:00Commented Dec 28, 2016 at 11:05
1 Answer
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).
2 Comments
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.