14.6 Overriding


14.6 Overriding

Overriding is the process of replacing an existing method in an inherited class with one more suitable for the new class. In the point and point3D examples appearing in the previous section, the distance method (presumably) computes the distance from the origin to the specified point. For a point on a twodimensional plane, you can compute the distance using the function:

However, the distance for a point in 3D space is given by the equation:

Clearly, if you call the distance function for point for a point3D object you will get an incorrect answer. In the previous section, however, you saw that the P3 object calls the distance function inherited from the point class. Therefore, this would produce an incorrect result.

In this situation the point3D data type must override the distance method with one that computes the correct value. You cannot simply redefine the point3D class by adding a distance method prototype:

 type      point3D:           class inherits( point )           var                z:int32;      method distance; // This doesn't work! endclass; 

The problem with the distance method declaration above is that point3D already has a distance method — the one that it inherits from the point class. HLA will complain because it doesn't like two methods with the same name in a single class.

To solve this problem, we need some mechanism by which we can override the declaration of point.distance and replace it with a declaration for point3D.distance. To do this, you use the override keyword before the method declaration:

 type      point3D:      class inherits( point )           var                z:int32;           override method distance; // This will work! endclass; 

The override prefix tells HLA to ignore the fact that point3D inherits a method named distance from the point class. Now, any call to the distance method via a point3D object will call the point3D.distance method rather than point.distance. Of course, once you override a method using the override prefix, you must supply the method in the implementation section of your code, e.g.,

 method point3D.distance; @ no display ;      << local declarations for the distance function>> begin distance;      << Code to implement the distance function >> end distance; 




The Art of Assembly Language
The Art of Assembly Language
ISBN: 1593272073
EAN: 2147483647
Year: 2005
Pages: 246
Authors: Randall Hyde

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net