Lesson 10
I am Your Father
Chapter 2: Inheritance
Why method overriding?
A practical use of method overriding is that you do not need to know in advance what specific type an object is.
For example, one can use a weapon to hurt a person. One does not need to know whether the weapon is a knife, a sword, a gun, a stick, a wand, a frying pan, or a nunchaku. As long as it is a weapon, one can use it to hurt someone! One also does not care how the weapon hurts someone, as long as it can do it!
The following example shows how this might work. No animals or humans were actually hurt in the process! Study the code below.
- Notice how each person has a different weapon (Lines 37-39).
- Also notice how each weapon hurts the victim differently (Lines 10-20).
- Note that Grandma Edna attacks a dog (Line 40), while the other two attack a person (Line 41-42). We did not add any special code to deal with this - they simply attack the animal, whether it’s a person or a dog!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
|
If you copy and run the above code, the output will be:
Grandma Edna attacks Bobby
Bobby is hit.
Frank the mugger attacks Grandma Edna
Grandma Edna is cut.
The Boss attacks Frank the mugger
Frank the mugger is shot.
As you can see, a Person
can use its weapon to hurt any animal (Line 33), whatever the weapon is. Depending on what weapon it is (Line 29), it will hurt the animal differently.
Similarly, it does not matter whether the animal victim is a person, a dog or a duck. A weapon can be used to hurt the animal.
Hopefully you can see the power of inheritance in action!