Java: Calling base class constructor

This entry is part 39 of 54 in the series Learn Java

Parameterized constructors have to be called manually by your program. This is also applicable to inheritance.

Suppose, a super class has a parameterized constructor, then it is the duty of the child class constructor to call the super class’s constructor first before executing any other Java statements inside its constructor, otherwise JVM will generate a compile time error.

Child class constructor will use super() method along with the required argument values to call super class constructor.

Finally, keep in mind that any other member functions apart from constructor cannot call super class’s constructor.

It is obvious that super class’s object will be constructed first before child class’s object construction.

package javaapplication29;

class Dog {

    String name;
    String colour;
    String diet;

    public Dog(String name1, String colour1, String diet1) {
        name = name1;
        colour = colour1;
        diet = diet1;

    public Dog(String colour1) {
        colour = colour1;

    public void eat(String food) {
        diet = food;

    public void bark() {
        System.out.println("Dog " + name + " can bark: Lol Lol Lol");

    public void showDog() {
        System.out.println("Dog name: " + name);
        System.out.println("Dog colour: " + colour);
        System.out.println("Dog can eat food: " + diet);
    public static void main(String[] args) {
        PetDog petDog = new PetDog("Tommy", "white", "meat", "Rajkumar");

        StrayDog strayDog = new StrayDog("black");

class PetDog extends Dog {

    String owner;

    public PetDog(String name, String colour, String diet, String owner1) {
        // super() should be the first statement
        super(name, colour, diet);
        owner = owner1;

    public void showLove() {
        System.out.println("Dog " + name + " can express love: Ich Ich Ich");

class StrayDog extends Dog {

    public StrayDog(String colour) {
    // super() should be the first statement
        // stray dog has only colour, and call overloaded constructor

    public void bite() {
        System.out.println("Beware: This stray Dog will bite");


Series Navigation<< Java: Basic concept of inheritance
Java: Method Overiding >>

Leave a comment

Leave a Reply