5.3. Method overriding

Suppose we need a TwoCounter object that increments its value by 2 instead of 1 each time nextValue is invoked. We could write a TwoCounter class from scratch en end up with a class very similar to Counter, but that wastes the effort we put in developing the Counter class and duplicates that effort in creating the TwoCounter class. The severity of this problem increases with the complexity of the classes and the effort needed to develop them, and to debug, test, document, etc.

Luckily, just like Counter inherits from State, TwoCounter can inherit from Counter. Since we need different behaviour for the nextValue message, the TwoCounter can provide its own nextValue method, overriding the method provided by Counter.


implementation class TwoCounter: Counter end;

implementation instance
TwoCounter

redefine int
  nextValue
{
  current_value += 2;
  = current_value;
}

end;

When nextValue is sent to a TwoCounter instance, the object will add 2 to its current_value and return the result. Apart from this method, a TwoCounter behaves exactly the same as a Counter.