Inheritance and Constructors

When a parent class has only constructors with parameters, the child class's constructor must call super(...) with those values as its first line.

Journeyman · Java · OOP · Updated

By

If the parent class has no constructor without parameters, the child class must call one of the parent's constructors with super(...). The keyword super is used whenever a child class needs to call the parent class’s constructor.

Character

This is the Character class that has been updated to include a constructor. Since this class only has one constructor a new Character can only be created by passing in 4 arguments.

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

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

    public Character(String name, int health, int level,
                int experience)
    {
        this.name = name;
        this.health = health;
        this.level = level;
        this.experience = experience;
    }

    // additional character code here

}

Archer

Since the Archer class extends Character, it must provide the super constructor with all 4 arguments.

public class Archer extends Character
{
    protected int arrows;

    public Archer(String name, int health, int level,
                int experience, int arrows)
    {
        // the call to the super constructor must be first
        super(name, health, level, experience);

        this.arrows = arrows;
    }

    // additional archer code here

}

Do it: build a knight with super(...)

Now Character has a constructor: every character needs a name, a health, a level and its experience. Every knight in the game starts with 120 health, at level 1 with 0 experience, and wears armor, so Knight asks only for a name and its armor.

The Character class is given. Its only constructor, Character(String name, int health, int level, int experience), sets all four, and it has a getter for each.

Knight's constructor gets two values:

  • name: the knight's name, such as "Lancelot".
  • armor: how much armor the knight wears, such as 5.

For example, new Knight("Lancelot", 5):

You ask for Comes from It gives
getName() name, passed on to Character's constructor "Lancelot"
getHealth() 120, passed on to Character's constructor 120
getLevel() 1, passed on to Character's constructor 1
getExperience() 0, passed on to Character's constructor 0
getArmor() armor, kept by Knight 5

Your job: finish the constructor Knight(String name, int armor).

  • It passes name, 120, 1 and 0 on to Character's constructor.
  • It sets the knight's own armor from its armor parameter.

As given, the starter doesn't compile yet: Java says Character's constructor can't be applied, because Knight doesn't call it. Fixing that is the first step.

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

Cheat sheets