oopxojo

OOP fundamentals: Mixing Superclass and subclass methods


Using two classes,
a baseclass called Super and
a subclass called Sub
each have two instance-methods with the exact same names (called m1 and m2).

At runtime an instance of Sub is created and Sub.m1 is called
Sub.m1 first calls Super.m1 (and runs a few extra lines of code afterwards)
Super.m1 calls the second method "m2".

Knowing that the runtime instance was of class Sub to begin with,
which of the two implementations of m2 gets executed Super.m2 or Sub.m2?


Solution

  • A simple call to m2 (which is short for self.m2) will be directed to the first m2 found when looking up the inheritance chain from this instance — because that is what self means.

    So if this instance is a Sub, then Sub's implementation of m2 is called if there is one, no matter where the calling method is located in the hierarchy.