Inheritance in Java

In Java, a child class inherits from a parent class with the extends keyword and then adds its own variables and methods.

Apprentice · Java · OOP · Updated

By

In Java, classes inherit from other classes by using the extends keyword. The parent (or super) class is coded as normal.

Character

public class Character
{
    protected static final int attackAmount = 10;

    private String name;
    private int health;
    private int level;
    private int experience;

    public boolean isDefeated() { return health <= 0; }
    public String getName() { return name; }
    public int getHealth() { return health; }
    public int getLevel() { return level; }
    public int getExperience() { return experience; }

    public void attack(Character target)
    {
        if (isDefeated()){ return; }

        target.takeDamage(attackAmount);
    }

    public void takeDamage(int damage)
    {
        this.health -= damage;
        if (isDefeated()) { health = 0; }
    }

    public void levelUp()
    {
        if(isDefeated()) { return; }

        this.level++;
        this.health += 10;
    }

    public String specialAbility() { return "Standard"; }
}

Archer

The Archer class extends Character. An archer has all the abilities of a character plus the additional attributes and methods defined here.

public class Archer extends Character
{
    private int arrows;

    public int getArrows() { return this.arrows; }

    public void addArrow()
    {
        arrows++;
    }
}

Do it: a wizard who casts spells

The game needs wizards. A wizard is a character, so it should get everything a character has, and add something of its own: mana, the magic it spends to cast spells.

The Character class is given. It has:

  • getName() and setName(String name): the character's name.
  • getLevel(): starts at 1, and levelUp() adds 1 to it.

Your Wizard gets its own variable and two methods:

  • mana: starts at 50.
  • getMana(): returns the mana.
  • castSpell(): a spell costs 10 mana. With at least 10 mana, it takes 10 away and returns true. With less than 10, the mana stays as it is and it returns false.

For example:

Wizard merlin = new Wizard();
merlin.setName("Merlin");
merlin.castSpell();
merlin.castSpell();
Step Mana castSpell() returns
A new wizard 50
castSpell() 50 − 10 = 40 true
castSpell() 40 − 10 = 30 true

So afterward, merlin.getMana() is 30, and merlin.getName() is "Merlin".

Your job: finish the class Wizard.

  • It inherits from Character.
  • It has a mana variable that starts at 50, and getMana() returns it.
  • It has the method castSpell(), as described above.
  • Nothing else: its name, its level and levelUp() come from Character.

Until Wizard inherits from Character, the tests can't compile: the Tests tab names the first method Wizard doesn't have yet.

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

Cheat sheets