next up previous contents
Next: Inheritance Up: The TOM Programming Language Previous: Return values   Contents

Objects

We now come to the most important subject of an object oriented programming language: how objects are constructed. We will use the Counter class first described in chapter 1 as the example along which to explain the object basics. From the informal description in that chapter we know the following:

1.
each Counter object maintains information about its current value, and
2.
it responds to the nextValue message by returning the next value, thereby updating its current value.

This description only contains statements about the Counter objects, i.e. instances of the Counter class. Therefore the class definition can be empty, for now.

implementation class Counter end;

The Counter instances maintain a current value, and respond to the nextValue method. This is written thus:

implementation instance Counter
{
  int current_value;
}
int
  nextValue
{
  current_value += 1;
  = current_value;
}

end;

The definition of the Counter instance starts with implementation instance Counter and ends with end;. Within this definition, between the first pair of braces an instance variable is defined. Instance variables form the state maintained by each instance of the current class: every Counter instance will have its own value of the current_value. This variable has the type int.

Following the instance variable declaration, the nextValue method is defined. This method has no arguments and returns an int. In the body of the method, the current_value instance variable of the current instance is incremented by 1, and the resulting value is returned. The current instance is the receiver of the message as a result of which the current method was invoked. Thus, in the following example

Counter count = ...;
int i = [count nextValue];

the count variable denotes a Counter instance; in the second line, the nextValue message is sent to it, and the nextValue method will be invoked, with the object we know as count as the receiver.




next up previous contents
Next: Inheritance Up: The TOM Programming Language Previous: Return values   Contents
Pieter J. Schoenmakers tiggr at gerbil.org