Solution to 8f65: Lucky battling fighters with inheritance
See code at solutions/code/tutorialquestions/question8f65
Compare the sample solution for this question with the sample solution for question 8d24. You will
see that in the new solution, the functionality that is common to all fighters is in the Fighter
class, while LuckyFighter overrides takeDamage and calculateDamage to
add testing of luck according to the three strategies. Look at the way super is used in these
methods to invoke the default behaviour. In particular, observe that the calculateDamage method
in LuckyFighter uses:
super.calculateDamage() * AGGRESSIVE_MULTIPLIER
and
super.calculateDamage() - MISS_PENALTY
to compute values for double damage and damage reduced by one. By invoking the superclass methods, instead of re-implementing their
behaviour, we ensure that any changes to calculateDamage in Fighter will be reflected in the increased or
reduced damage calculations in LuckyFighter. To be specific: currently, calculateDamage in Fighter
returns 2. However, if we decided to change this method to return, e.g., 4, or to return a value computed from the fighter's skill attribute,
LuckyFighter's calculateDamage method would still have the desired effect of doubling, or reducing by one, this new value
when a fighter tests his/her luck.
Main.java shows that a LuckyFighter can be used exactly like a Fighter is used:
Fighter elfLord = new LuckyFighter("Alex", "Elf Lord", 18, 6, 11, Strategy.Defensive, gameEngine);
creates a new LuckyFighter and assigns a reference to this object to elfLord, which
has type Fighter.