[Tutor] Calling method in parent class

Alan Gauld alan.gauld at btinternet.com
Wed May 13 00:23:02 CEST 2009


"spir" <denis.spir at free.fr> wrote

>> Two methods only one message. It is what polymorphism is all about.
> 
> Well, I do not want to argue. But this is not what I call polymorphism.
> Not "on the same object". Polymorphism as I know it rather dispatches 
> depending on the object (usually it's actual type).

Yes, the two methiods are in different classes.

But it is totally normal for a polymorphic method to call the code in 
the base class for that same method. In my experience that is more 
common than not doing it. It would be very suspicious to me to be 
overriding a method and *not* calling the base class (unless the base 
class was a pure abstract class - aka an interface)  since that would 
imply that the methods were semantically different.

> The kind of exception beeing the case of one method calling 
> the other (as I related later in the same post). But it still is not is 
> calling 2 methods with the same name on the same object. 
> It's rather one method reusing another.

Yes, that would be self messaging which is a different thing altogether
But calling the method of a superclass from the same method is very, 
very common. 

Bjarne Stroustrup describes this practice in "The C++ Programming 
Language" as: 
---------- quote -------
"The cleanest solution is for the derived class to use only the public 
members of its base class. For example

void Manager::print() const
{   Empoyee::print()  // print Employee info
     cout << level;  // print Manager specific info
};

Note that :: must be used because print has been redefined in manager. 
SUCH REUSE OF NAMES IS TYPICAL 
--------------end quote--------------
(caps mine)

Although Python is not C++ it makes no difference in this case, 
the principle is the same.

And Grady Booch says in his OOAD book when discussing a 
method  defined as:

------------- quote ----------
void ElectricData::send() {
    TelemetryData::send()
    // transmit the electric data
}

Most OO languages permit the implementation of a subclass's 
method to invoke a method defined in some super class. As this 
exampler shows IT IS COMMON for the implementation  of a 
redefined method TO INVOKE THE METHOD OF THE 
SAME NAME DEFINED BY A PARENT CLASS.

....<discussion of various languiage implementations of same>...

In our experience, a developer USUALLY NEEDS TO INVOKE 
A SUPERCLASS METHOD EITHER JUST BEFORE OR 
AFTER DOING SOME OTHER ACTION. In this way subclass 
methods play a role in AUGMENTING THE BEHAVIOUR 
DEFINED IN THE SUPERCLASS.
------------- end quote ----------
(caps mine)

So at least two well known OOP authorities recognise that such 
is common practice.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list