java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to 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 com.javacoderanch.example.fundametal;

public class Human {
    private String sex;
    private int age;
    
    public Human(String sex) {
        this.sex = sex;
    }
}

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 com.javacoderanch.example.fundametal;

public class Female extends Human {
    private String hairStyle;
    
    public Female(String hairStyle, String sex) {
        super(sex);
        this.hairStyle = hairStyle;
    }
}