Inheritance and Constructors in Java
Last Updated :
19 Jul, 2022
Constructors in Java are used to initialize the values of the attributes of the object serving the goal to bring Java closer to the real world. We already have a default constructor that is called automatically if no constructor is found in the code. But if we make any constructor say parameterized constructor in order to initialize some attributes then it must write down the default constructor because it now will be no more automatically called.
Note: In Java, constructor of the base class with no argument gets automatically called in the derived class constructor.
Example:
Java
class Base {
Base()
{
System.out.println(
"Base Class Constructor Called " );
}
}
class Derived extends Base {
Derived()
{
System.out.println(
"Derived Class Constructor Called " );
}
}
class GFG {
public static void main(String[] args)
{
Derived d = new Derived();
}
}
|
Output
Base Class Constructor Called
Derived Class Constructor Called
Output Explanation: Here first superclass constructor will be called thereafter derived(sub-class) constructor will be called because the constructor call is from top to bottom. And yes if there was any class that our Parent class is extending then the body of that class will be executed thereafter landing up to derived classes.
But, if we want to call a parameterized constructor of the base class, then we can call it using super(). The point to note is base class constructor call must be the first line in the derived class constructor.
Implementation: super(_x) is the first line-derived class constructor.
Java
class Base {
int x;
Base( int _x) { x = _x; }
}
class Derived extends Base {
int y;
Derived( int _x, int _y)
{
super (_x);
y = _y;
}
void Display()
{
System.out.println( "x = " + x + ", y = " + y);
}
}
public class GFG {
public static void main(String[] args)
{
Derived d = new Derived( 10 , 20 );
d.Display();
}
}
|