-1

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

2

1 Answer 1

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).

Sign up to request clarification or add additional context in comments.

2 Comments

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.
yep, you're right. I'm changing the code

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.