[racket] Overriding methods in Racket classes
Sorry -- typo in my code, my last email should read:
OK using define-local-member-name works, see case 1 below, but it
seems it would be much simpler if there was a form define/inheritable
which made the method accessable within the class body where it was
defined and in the sub-class bodies only. (see case 2 below)
i.e. no wrapping in a let that returned multiple values etc.
Is there some reason there isn't such a form define/inheritable ?
===================================
Case 1 (using define-local-member-name)
=================================
#lang racket
(define-values (fish% picky-fish%)
(let ()
(define-local-member-name grow)
(define fish% (class object%
(init size) ; initialization argument
(define current-size size) ; field
(super-new) ; superclass initialization
(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)))))
(define picky-fish% (class fish% (super-new)
(define/override (grow amt)
(super grow (* 3/4 amt)))))
(values fish% picky-fish%)))
(define joe-the-minnow (new fish% [size 2]))
(define bud-the-minnow (new fish% [size 2]))
(define big-al-the-pike (new fish% [size 10]))
(define picky-selma (new picky-fish% [size 5]))
(send picky-selma eat joe-the-minnow)
(send picky-selma get-size)
;;this now correctly fails
;(send bud-the-minnow grow 5)
====================================
(Case 2 using a hypothetical define/inheritable)
====================================
#lang racket
(define fish% (class object%
(init size)
(define current-size size)
(super-new)
(define/public (get-size)
current-size)
(define/inheritable (grow amt) ;;;hypothetical define/inheritable
(set! current-size (+ amt current-size)))
(define/public (eat other-fish)
(grow (send other-fish get-size)))))
(define picky-fish% (class fish% (super-new)
(define/override (grow amt)
(super grow (* 3/4 amt)))))
(define joe-the-minnow (new fish% [size 2]))
(define bud-the-minnow (new fish% [size 2]))
(define big-al-the-pike (new fish% [size 10]))
(define picky-selma (new picky-fish% [size 5]))
(send picky-selma eat joe-the-minnow)
(send picky-selma get-size)
Thanks,
Harry Spier