我有一个包含几个子类的类,它们都使用父类的方法和字段。是否有“正确”的处理方法?
到目前为止,我一直在每个子类中使用(inherit method1 method2 ...)
。
我徒劳地搜索了一种方法,即父类可以强制子类继承绑定,我理解这可能是糟糕的风格。
对Racket或OOP不太熟悉。
答案 0 :(得分:2)
即使您不使用inherit
,也会继承这些方法。
要从超类调用方法,可以使用(send this method arg1 ...)
。
类表单中的表单(inherit method)
将使该方法在正文中以(method arg1 ...)
形式提供。这不仅是一种方便的简写,而且比(send this method)
更有效。
我不知道要继承包名称的表单,但是你可以使用一个小的宏来自行编写。这是一个例子:
(define-syntax (inherit-from-car stx)
(datum->syntax stx '(inherit wash buy sell)))
(define car% (class object%
(define/public (wash) (display "Washing\n"))
(define/public (buy) (display "Buying\n"))
(define/public (sell) (display "Selling\n"))
(super-new)))
(define audi% (class car% (super-new)
(inherit-from-car)
(define/public (wash-and-sell)
(wash)
(sell))))
(define a-car (new audi%))
(send a-car wash-and-sell)