Inheritance and Constructors in Java
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.
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.
x = 10, y = 20
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Please Login to comment...