[ parent-object-type ] OBJECT object-fields [ METHODS methods ] [ OVERRIDES overrides ] END
An object is a record paired with a method suite: a collection of procedures that operate on the object. The fields of an object are specified just like those of records (see section Record Types). Methods look like fields that hold procedure values. They are specified as follows:
methods = { method ";" ... }
where method = identifier signature [ ":="
procedure-name ]
A method signature is similar to a procedure signature (see section Procedure Types). If a procedure name follows ":=", the signature of the procedure must have as its first parameter an object of the type we are declaring; the rest of the parameters much match signature. The first parameter is often refered to as the self parameter.
Overrides specify new implementations for methods declared by an ancestor object-type:
overrides = { override ";" ... }
where
override = method-name ":=" procedure-name
Let's create an object type Polygon which contains an open array of coordinates. We also have an initialization method, init, and a verification method, verify, which will be done by each subclass.
TYPE Polygon = OBJECT coords: REF ARRAY OF Point.T; METHODS init(p: ARRAY OF Point.T): Polygon := Init; verify() := NIL; (* To be overridden by subclasses. *) END; PROCEDURE Init (self: Shape; p: ARRAY OF Point.T) = BEGIN self.coords := NEW(NUMBER(p)); self.coords^ := p; self.verify(); (* Make sure initialization is OK. *) RETURN self; END;
Type Drawable adds the draw method to Polygon and assigns the Draw procedure as the default implementation for the draw method.
TYPE Drawable = Shape OBJECT METHODS draw() := Draw; END;
PROCEDURE Draw (shape: Drawable) = BEGIN WITH p = shape.coords^ DO FOR i = FIRST(p) TO LAST(p)-1 DO DrawLine(p[i], p[i+1]) END; DrawLine(p[LAST(p)], p[FIRST(p)]); END; END;
Type Rectangle is a concrete implementation of an object. It will override the verify method to make sure there are four sides to this polygon and that the sides have the right properties.
TYPE Rectangle = Drawable OBJECT METHODS OVERRIDES verify := Verify; END; PROCEDURE Verify (rect: Rectangle) = BEGIN WITH p = rect.coords^ DO <* ASSERT NUMBER(p) = 4 *> <* ASSERT p[0].h = p[3].h *> ... END END Verify;