Java Notes

Constructor Chaining Exercise 1

Name _______________________________

The first line of every constructor must be either

If no constructor call is written as the first line of a constructor, the compiler automatically inserts a call to the parameterless superclass constructor.

Question

What is printed by this program?

// File   : ConstructorChain.java
// Purpose: Illustrate constructor chaining.
// Author : Fred Swartz
// Date   : 5 May 2003


class ConstructorChain {
    public static void main(String[] args) {
        Child c = new Child();
    }
}


class Child extends Parent {
    Child() {
        System.out.println("Child() constructor");
    }
}


class Parent extends Grandparent {
    Parent() {
        this(25);
        System.out.println("Parent() constructor");
    }
    
    Parent(int x) {
        System.out.println("Parent(" + x + ") constructor");
    }
}


class Grandparent {
    Grandparent() {
        System.out.println("Grandparent() constructor");
    }
}

You can check your answer with Constructor Chaining Answer.