Inheritance via Delegation

So, our objects now have local state variables and message passing. What about inheritance? We can provide that capability using the technique of delegation. Each instance of the child class contains an instance of the parent class, and simply passes on the messages it doesn’t want to specialize:


This script implements the buzzer class, which is a child of counter. Instead of having a count (a number) as a local state variable, each buzzer has a counter (an object) as a local state variable. The class specializes the next method, reporting what the counter reports unless that result is divisible by 7, in which case it reports “buzz.” (Yeah, it should also check for a digit 7 in the number, but this code is complicated enough already.) If the message is anything other than next, though, such as reset, then the buzzer simply invokes its counter’s dispatch procedure. So the counter handles any message that the buzzer doesn’t handle explicitly. (Note that in the non-next case we call the counter, not ask it something, because we want to report a method, not the value that the message reports.) So, if we ask a buzzer to reset to a value divisible by 7, it will end up reporting that number, not “buzz.”