Difference between extending types and classes |
Thus if a variable has a type, then any object from a class implementing that type can be associated with that variable. If a formal parameter has a type then any object from a class implementing the type can be used as an actual parameter in that slot.
We can also extend types using the & operation. If T and U are types then the type T & U contains all the methods of T and U. We can also extend a type to form a new type with more methods using &.
type T = U & type { m ->Done n(x:Number) -> String }
Notice that if the second type is given by a list of methods then Grace syntax insists that we insert the keyword type just before the list of methods.
We use this to extend types throughout the objectdraw library. For example, look at the definition of Graphic2D:
type Graphic2D = Graphic & type { // dimensions of object width -> Number height -> Number ... }
and
type Line = Graphic & type { // Contains everything in Graphic plus ... // start and end of line start -> Point end -> Point ... }
Recall that we can associate an object with an identifier of type T as long as it has at least the methods of T. In particular, because Graphic2D is an extension of Graphic and classes like framedRect, filledOval, etc. all generate objects of type Graphic2D, they can also be associated with identifiers of type Graphic, as they also have all the methods of Graphic.
A bit of terminology, if type U has all the methods of type T (and perhaps more) then we say that U is a subtype of T and that T is a supertype of U. Thus Graphic2D is a subtype of Graphic and Graphic is a supertype of Graphic2D.
A type can be a subtype of another even if they are defined completely independently. All they need is of all the methods in the supertype to also be in the subtype (with the same parameter and return types).
Grace also allows the programmer to specialize the return type of a method in a subtype (or subclass), but we won't need that here.
Finally note that there is a lot of inheritance in the objectdraw library. We took a quick look at the code for graphic items to see how that worked.
Difference between extending types and classes |