Defining Classes

A class definition can restrict the values of any slot to a particular C-style type. It can specify whether a slot is private (the default, meaning that it cannot be accessed except by that methods of that class), protected (like private, except that the slot can also be accessed by subclasses of the class), or public (meaning get and put methods for the slot are generated automatically), and it can specify an initial value. The class definition also may contain method clauses, which determine how instances of the class will respond to messages. A class definition may also specify one or more superclasses and which methods are to be inherited.

The point object created in the previous example had two floating point slots, named x and y, with initial values of 1.0 and 2.0, respectively. As we have seen, the point class also defined put and get methods for x and y, as well as a send method for printing the object. The put and get methods for x and y can be automatically generated simply by declaring the slots public, but the print method must be explicitly written. In addition, in order to be able to create instances of this class, we must define a create method, as explained in obj-scl-meth-credes. We also provide a second create method, taking two arguments, allowing us to specify an x and y value when we first create a point object.

     :- class point =
             [public x:float = 1.0,
              public y:float = 2.0].
     Self <- create.
     Self <- create(X, Y) :-
             Self << x(X),
             Self << y(Y).
     Self <- print(Stream) :-
             Self >> x(X),
             Self >> y(Y),
             format(Stream, '(~w,~w)', [X,Y]).
     :- end_class point.

The variable name Self in these clauses is arbitrary--any variable to the left of the message operator in the head of a method clause refers to the instance of the class receiving the message.