Lesson 10
I am Your Father
Chapter 2: Inheritance
Method overriding
Back to our RPG example! Let us now implement the Monster class. 👾

Remember that Enemy has an evil_laugh() method that prints out Hehehehehe!
Monster will naturally inherit this method. But Monster actually laughs quite differently from its Enemy superclass. So we need to let it have its own evil laughter rather than following the Enemy laughter! 👾👾👾
1 2 3 4 5 6 7 8 9 10 11 12 | |
If you run the code above (you will also need Character and Enemy), you will find that the monster now has its own customised evil laugh. WAHAHAHAHAHAHAHAHAHA!!! HA!!
This is called method overriding. You basically replace the superclass’ method with your own.
Accessing a superclass’ method
Say you now need Monster to first laugh like an Enemy and then add its own custom laugh to it (because all Enemy must start by laughing that way!)
Use super() to access the superclass Enemy’s version of evil_laugh() (Line 8).
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
Your output should now say:
Hehehehehe!
WAHAHAHAHAHAHAHAHAHA!!! HA!!