![]() |
|||||||||
| 6.5 Extending Inherited Methods
|
|||||||||
|
Extending an inherited method is a variation of replacing a method. The distinguishing features of extending an inherited method is that the extending method in the derived class overrides the inherited method (i.e., the extending method has the same signature as the inherited method), and invokes the inherited method to perform part of its work. Because the overriding method itself uses the method that it overrides, it appears to extend the inherited method by adding new actions to the method's execution . An example of extending an inherited method occurs in the Cycler class. As the class was defined earlier, it inherits a Reset method from the DisplayableNumber class. However, this inherited method allows any number to be entered by the user - possibly one outside the range of the Cycler. If this occurred, the program could access this erroneous value, via the Value method. To prevent this problem from occurring, a safer (more restricted) Reset method is needed in the Cycler class. To override and extend the inherited Reset method, the Cycler class would be redefined as shown below.
In this method, the overriden base class method is itself invoked. To distinguish between the two Reset methods, the syntax "DisplayableNumber::Reset" is used in the Cycler's Reset method to indicate the Reset method in the base class (DisplayableNumber). Without this additional syntax to specify the base class name, it would be assumed that the Cycler's Reset method was making a recursive call on itself, when that is clearly not what is desired here. The figure below, using the Cycler class as an example, depicts the sequence of events that occurs when an extended method is executed. In step 1, an invocation of the Reset method occurs. Because the derived class method overrides the inherited method, this invocation will result in the execution of the derived class method (Cycler::Reset). In step 2, the derived class method invokes the inherited method (DisplayableNumber::Reset). When the base class method returns, in step 3, it returns to the Cycler::Reset method. Finally, in step 4, the derived class method returns, completing the invocation. Because the control begins and ends in the derived class method, the derived class method can perform any necessary preprocessing actions before invoking the base class method (after step 1 and before step 2) and can perform any necessary postprocessing actions before returning (between steps 3 and 4).
|
|||||||||
|
|||||||||