5.13.2. Objects with Methods

In addition to variables, an object can contain methods. The idea is that an object's methods work with the object's variables.

If object x contains a method called m, then x.m is that method. Use it as you would any other method. For example, suppose that object duck contains a procedure called swim that takes one integer parameter. Then

  duck.swim(4);
performs duck's swim method with argument 4. If duck also contains a method called getBeakSize that takes no parameters and yields a result of type double, then
  double beaksize = duck.getBeakSize();
sets variable beaksize to the value that duck's getBeakSize method returns.


Accessors and mutators

An object often (but not always) contains methods, called accessors, whose job is to get the value of one of the object's varaibles. By convention, an accessor has a name that starts with get.

An object also often (but not always) contains methods, called mutators, whose job is to store a value into one of the object's variables. By convention, mutators have names that begin with set.

Generalizing the ideas of accessors, an accessor yields a property of an object without changing the information stored in the object. The property is not necessarly stored in a variable, but it can be computed from the information in the variables.

Similarly, a generalized mutator is a method that alters what is stored in the object in some way.

You do not really need to know anything about the variables in an object to use accessors and mutators. You only need to have a mental model of the object, and of how the accessors and mutators work in your mental model. Your mental model might not correspond directly to the variables that the object contains.