In java, there exists a very important keyword known as super() keyword in java which is widely used in java being object-oriented and hence inheritance comes into play. So whenever we use super keyword inside a child constructor then it calls the default parent constructor by itself.
Example 1
Java
// Java Program to Demonstrate Inherited constructor // calls the parent constructor by default // Class 1 // Main class class GFG {
public static void main(String[] a)
{
// Inherited constructor calling
new child();
new parent();
}
} // Class 2 // Parent class - Helper class class parent {
// Constructor of parent class
parent()
{
System.out.println( "I am parent class constructor" );
}
} // Class 3 // Child class - Helper class class child extends parent {
// Constructor of child class
child()
{
System.out.println( "I am child class constructor" );
}
} |
Output
I am parent class constructor I am child class constructor I am parent class constructor
Example 2
Java
// Java Program to Demonstrate Inherited constructor // calls the parent constructor by default // Class 1 // Main class class GFG {
// Main driver method
public static void main(String[] a)
{
// Inherited constructor calling
new child();
new child( 100 );
}
} // Class 2 // Parent class (Helper class) class parent {
// Constructor of parent class
parent()
{
// Print statement
System.out.println( "I am parent class constructor" );
}
} // Class 3 // Child class (Helper class) class child extends parent {
// Constructor 1
// Constructor of child class
child()
{
// Print statement
System.out.println( "I am child class constructor" );
}
// Constructor 2
// Constructor of child class
child( int x)
{
// Print statement
System.out.println(
"I am param child class constructor" );
}
} |
Output
I am parent class constructor I am child class constructor I am parent class constructor I am param child class constructor