Java: What exactly is immutable?

In a nutshell, an object is immutable if it's state can not change. This definition however, begs the question: What belongs to the objects state? Suppose we have

class Person {
    final StringBuffer name = new StringBuffer();
}

The name reference of the Person object itself is final so it can not change, but since StringBuffer is mutable the actual name of the person can change. So, is Person mutable or not?

Most people would agree that objects of this class are mutable. So a more precise definition of immutable would be:

An object is immutable if

  • it's own state is immutable, and
  • the states of all objects directly or indirectly reachable from it's state, are immutable.

Comments

Be the first to comment!