Mutable vs. Immutable Objects

The previous object has no methods for changing the values of the object, aside from changing the fields directly with an assignment statement.

A way to enforce the non-changeability of those fields is to declare them private:

class pair
{
private int x;
private int y;
... rest as before ....
}

 

Now there is no way to change the values in the object once it is created.

Such objects are called immutable.

Functional programming, in a sense, deals only with immutable objects.

 

If we add a setter capability, such as setX, setY, then the objects in the class would be mutable.

 

void setX(int x)		// set the x value
  {
  this.x = x;
  }

 

int setY(int y)		// set the y value
  {
  this.y = y;
  }

Note that these methods would change the value returned by min, as well as the values returned by getX and getY.

 

Next Slide Previous Slide Contents