State-Sensitive Methods

Consider the following class, with two getters:

class pair
{
int x;
int y;

 

pair(int x, int y)	// construct from x and y values
  {
  this.x = x;
  this.y = y;
  }

 

int getX()		// get the x value
  {
  return x;
  }

 

int getY()		// get the y value
  {
  return y;
  }
}

 

When we call a getter thus:

pair p;
p = new pair(7, 11);

 

System.out.println(p.getY());

 

the value 11 is printed. Note that there is no argument to getY.

The value 11 comes about by virtue of this call being relative to the object p, not because of a functional dependency of the result on the argument.

 

Likewise, were we to augment the class pair with a method min:

 

class pair
{
.... other stuff ....

 

int min()
  {
  return x < y ? x : y;
  }
}

 

we'd get from

System.out.println(p.min());

the value 7.

Next Slide Previous Slide Contents