How do I invoke superclass constructor?

This example shows you how to use the super keyword to call a superclass constructor. The Female class constructor calls its superclass constructor and initializes its own initialization parameters. The call to the superclass constructor must be done in the first line of the constructor in the subclass.

package org.kodejava.example.fundamental;

public class Human {
    private String gender;
    private int age;

    public Human(String gender) {
        this.gender = gender;
    }
}

To call a superclass constructor we call super(). In the case below we call the superclass constructor with one string variable as a parameter.

package org.kodejava.example.fundamental;

public class Female extends Human {
    private String hairStyle;

    public Female(String hairStyle, String gender) {
        super(gender);
        this.hairStyle = hairStyle;
    }
}

How do I use the super keyword?

When a class extends from other class, the class or usually called as subclass inherits all the accessible members and methods of the superclass. If the subclass overrides a method provided by its superclass, a way to access the method defined in the superclass is through the super keyword.

package org.kodejava.basic;

public class Bike {
    public void moveForward() {
        System.out.println("Bike: Move Forward.");
    }
}

In the ThreeWheelsBike‘s moveForward() method we call the overridden method using the super.moveForward() which will print the message from the Bike class.

package org.kodejava.basic;

public class ThreeWheelsBike extends Bike {
    public static void main(String[] args) {
        Bike bike = new ThreeWheelsBike();
        bike.moveForward();
    }

    @Override
    public void moveForward() {
        super.moveForward();
        System.out.println("Three Wheels Bike: Move Forward.");
    }
}