On this page:

4 Class 2

 #lang class/2

(require module-name ...)
Imports all the modules named module-names.

(provide id ...)
Makes all of the ids available to other modules.

(define-class class-name
  method-spec ...)
super-spec = 
  | (super super-name)
implements-spec = 
  | (implements interface-name ...)
fields-spec = 
  | (fields field-name ...)
constructor-spec = 
  | (constructor (arg ...) body ...)
method-spec = 
(define (method-name arg ...)
Defines a new class named class-name, much like as with class/0, however a class may declare super-name as a super class of class-name by using (super super-name). A class may also declare to implement a number of interfaces using (implements interface-name ...).

When a class definition declares a super class, it inherits all of the super class’s fields and methods.

If a method definition defines the same method name as a method in the super class, then that method definition overrides the definition in the super class. The super class method can be called with

If no constructor-spec is provided, the default constructor simply accepts as many arguments as the class has fields, and initializes them in positional order, with subclass arguments before superclass arguments.

If a constructor-spec is provided, then constructing the object takes as many arguments as the constructor-spec has args. The provided values are bound to the args, and the body of the constructor is run. The constructor must use the fields form to produce values to use to initialize the fields of the object.

The constructor for the class takes values for its fields followed by values for the fields of the super class.

> (define-class c%
    (fields x)
    (define (m) 'm!))
> (define-class d%
    (super c%)
    (fields y)
    (define (n) 'n!))
> (define d (new d% 'y! 'x!))
> (send d m)


> (send d n)


> (send d x)


> (send d y)


> (define-class mul%
    (fields a b prod)
    (constructor (x y)
      (fields x y (* x y))))
> (new mul% 5 7)

(object:mul% 5 7 35)

When a class definition declares to implement any interfaces, it must define all the methods of the interfaces, otherwise an error is signalled.

(super class-or-interface-name)
(implements interface-name ...)
(constructor (args ...) body)

(fields id ...)
(define (method-name id ...) body)
(new class-name arg ...)
(field field-name)
(send object message arg ...)
These have the same meaning as in class/1.

(define-interface interface-name
  (super super-interface) ...
  (method-name ...))
Defines a new interface named interface-name. Classes declaring to implement interface-name must provide methods implementing each of the method-names, as well as all methods declared in any of the super-interfaces. The super-interfaces must name previously defined interfaces.