3.2.2 Relationship between classes and methods

The relationship between classes and methods in Dylan is different from that in C++ and Smalltalk, among other languages.

Comparison to C++ and Smalltalk: In C++ and Smalltalk, a class contains the equivalent of methods. In Dylan, a class does not contain methods; instead, a method belongs to a generic function. This design decision enables these powerful features of Dylan:

  • You can define methods on built-in classes (because you do not have to modify the class definition to define a method intended for use on the class). For an example, see Section 6.1, page 75. More generally, you can define a method for a class that you did not define.

  • You can write multimethods. In a multimethod, the method dispatch is based on the classes of more than one argument to a generic function. For an introduction to method dispatch, see Section 5.5, page 63. For information about multimethods, see Chapter 6, Multimethods.

  • You can restrict generic functions to operate on specific classes of objects.

In Dylan, a method belongs to a generic function, as shown in Figure 3.1, page 30. Although methods are independent of classes, methods operate on instances of classes. A method states the types of objects for which it is applicable by the type constraint of each of its required parameters. Consider the say-greeting method defined earlier:

define method say-greeting (greeting :: <integer>);
  format-out("Your lucky number is %s.\n", greeting);
end;

This method operates on instances of the <integer> class. Notice how easy and convenient it is to define a method intended for use on the built-in class <integer>.