Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Java Program to Show Inherited Constructor Calls Parent Constructor By Default

  • Last Updated : 24 Sep, 2021

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 inheritence comes into play. So whenever we use super keyword inside a child constructor then it calls the default parent constructor by itself.

Example 1

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

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

 




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!