Overriding Methods

Override an inherited method with @Override and call super to keep the parent's logic while adding your own.

Journeyman · Java · OOP · Updated

By

It is often necessary to modify the logic of an inherited method. For example, a character object has the ability to levelUp(). When a character levels up, their level increases by 1, but their health also increases by 10.

An archer inherits this functionality, but the logic needs to be slightly altered: the archer should receive an arrow each time they level up. This means that you need to override the default levelUp() method logic.

In this example, super.levelUp() runs the levelUp() code written in the Character class, and this.arrows is the archer's own variable. Both work on the same archer object. We need to use the super.levelUp() method call to execute the code that was defined in the character class.

public class Archer extends Character
{
    // class definition here

    @Override
    public void levelUp()
    {
        super.levelUp();
        this.arrows++;
    }
}

Do it: a wizard who levels up its own way

When a wizard levels up, it does everything a character does, and its mana grows by 20 too. A wizard's special ability isn't the standard one either: it's "Fireball".

The Character class is given. It has:

  • getName(), getLevel() and getHealth(). A new character is at level 1 with 100 health.
  • levelUp(): adds 1 to the level and 10 to the health.
  • specialAbility(): returns "Standard".

The Wizard class is started for you: its constructor, and a mana variable that starts at 50, with getMana().

For example:

Wizard merlin = new Wizard("Merlin");
merlin.levelUp();
Level Health Mana
A new wizard 1 100 50
After levelUp() 1 + 1 = 2 100 + 10 = 110 50 + 20 = 70

And merlin.specialAbility() returns "Fireball".

Your job: add two overrides to Wizard.

  • levelUp(): does everything Character's levelUp() does, then adds 20 to mana.
  • specialAbility(): returns "Fireball".
  • Mark each one with @Override.

Practiced live on the lesson page: write the Java right there and check it.

Cheat sheets