[Tutor] impact of OO

Erik Price erikprice@mac.com
Sun, 7 Apr 2002 18:55:21 -0400


On Friday, April 5, 2002, at 05:19  AM, alan.gauld@bt.com wrote:

> There are other aspects to OOP too that we haven't
> touched on. The ease of extending existing code without
> changing it (and thus breaking existing code relying
> on the bit being extended) via inheritance. The way
> OOP eliminates long if/elif/else chains (or switch
> statements)via polymorphism (see the OOP page in my
> tutor for a discussion of polymorphism and inheritance)

Hm... I understand the idea of inheritance (that a class can extend 
another class, making a more-specific subclass).  But polymorphism, 
though I had seen the term bandied about, wasn't very clear to me until 
I read the relevant page in your tutor.  I'd like to make sure that I 
understand what it is, though.

It sounds as though it's really nothing more than a way of taking 
several different classes which might be used in similar (though 
different) ways, and giving them identical method names so that they can 
be accessed without having to write special-circumstance code that 
applies specifically to that particular class.  The example you provide 
on your web page seems perfect -- assign a name to all elements in an 
array ("shape"); use that name to access the contents of those elements; 
use a single method call (".calculateArea") to perform work on each 
object in the contents of those elements.  If you did not use this 
technique, then you would have to check for the type of object and do 
something like "if shape isanobject(triangle) then... else if shape 
isanobject(square) then...".

That's what it seems like -- so polymorphism is really just a term for 
abiding by a certain convention in naming class methods.  Is this a 
correct interpretation?

If so, then this leads directly to the concept of overriding, which I 
have also just recently learned of -- that a subclass of a parent class 
contains a method with the same name as a method in the parent class, so 
that the subclass's method supplants the parent class's method.  I'm 
sure that the reason why you would ever want to do this will come to me 
someday in the future when I have a chance to do some advanced 
programming with classes and inheritance, but for now it doesn't seem to 
be very worthwhile to me when you could just give the subclass its own, 
different, method name.  Unless you were trying to use a trick like 
polymorphism, in which case having the same name, so that you do not 
need to customize the code that calls the method, would be beneficial.


Erik