-1

Can anyone explain me on a simple example the difference between mutable and immutable objects in java?

SwaggyP
  • 1
  • 2
  • 1
    I'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
  • 9
    Here's a good link about the subject: http://stackoverflow.com/questions/214714/mutable-vs-immutable-objects – barreira Dec 28 '16 at 11:05

1 Answers1

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
  • 1
    To 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
  • yep, you're right. I'm changing the code – Mark Bramnik Dec 28 '16 at 11:58