Java Program to Show Inherited Constructor Calls Parent Constructor By Default
Last Updated :
28 Jan, 2022
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
class GFG {
public static void main(String[] a)
{
new child();
new parent();
}
}
class parent {
parent()
{
System.out.println( "I am parent class constructor" );
}
}
class child extends parent {
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
class GFG {
public static void main(String[] a)
{
new child();
new child( 100 );
}
}
class parent {
parent()
{
System.out.println( "I am parent class constructor" );
}
}
class child extends parent {
child()
{
System.out.println( "I am child class constructor" );
}
child( int x)
{
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
Share your thoughts in the comments
Please Login to comment...