-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path09_classes_and_objects.rkt
42 lines (37 loc) · 1.23 KB
/
09_classes_and_objects.rkt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#lang racket ; defines the language we are using
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 9. Classes and Objects
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Create a class fish% (-% is idiomatic for class bindings)
(define fish%
(class object%
(init size) ; initialization argument
(super-new) ; superclass initialization
;; Field
(define current-size size)
;; Public methods
(define/public (get-size)
current-size)
(define/public (grow amt)
(set! current-size (+ amt current-size)))
(define/public (eat other-fish)
(grow (send other-fish get-size)))))
;; Create an instance of fish%
(define charlie
(new fish% [size 10]))
;; Use `send' to call an object's methods
(send charlie get-size) ; => 10
(send charlie grow 6)
(send charlie get-size) ; => 16
;; `fish%' is a plain "first class" value, which can get us mixins
(define (add-color c%)
(class c%
(init color)
(super-new)
(define my-color color)
(define/public (get-color) my-color)))
(define colored-fish% (add-color fish%))
(define charlie2 (new colored-fish% [size 10] [color 'red]))
(send charlie2 get-color)
;; or, with no names:
(send (new (add-color fish%) [size 10] [color 'red]) get-color)