4 Class 2
#lang class/2 | package: base |
syntax
(require module-name ...)
syntax
(provide id ...)
syntax
(define-class class-name super-spec implements-spec fields-spec constructor-spec 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 ...) body)
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) 'm!
> (send d n) 'n!
> (send d x) 'x!
> (send d y) '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.
syntax
(super class-or-interface-name)
syntax
(implements interface-name ...)
syntax
(constructor (args ...) body)
syntax
syntax
syntax
(fields id ...)
syntax
(define (method-name id ...) body)
syntax
(new class-name arg ...)
syntax
syntax
(send object message arg ...)
syntax
(define-interface interface-name (super super-interface) ... (method-name ...))