Constructor Chaining
So, this week, I happened to recall myself of one really intimidating thing that had been bothering since I started learning java in a bit depth. And it was Constructor Chaining.
From what I understand now it is pretty simple.
Basically, Constructor Chaining as even its name suggests, one constructor seems to be calling another one. That is, calling one constructor from another constructor is called constructor chaining in Java.
Basically, Constructor Chaining as even its name suggests, one constructor seems to be calling another one. That is, calling one constructor from another constructor is called constructor chaining in Java.
Now, we can do this by either using this keyword (for calling one constructor from another constructor in the same class) and super keyword (for calling constructor from the base/super class)
My initial confusion regarding constructor chaining was that no matter what, whenever we create the object/instance of child class (or call child class constructor) a call to default constructor is automatically made first. But this is true only when we have not explicitly called any other constructor from our child class constructor
For example:-
For example:-
Class First{
First(){
System.out.print("Hello");
}
Class Second extends First{
Second(int i)
{
System.out.println("Blogger");
}
Second(){} // not explicitly calling any other constructor either using this() or super()
Code:
Second s = new Second();
Output: Hello
*Note:- Since we have a parametrized constructor it is onto us to define the default constructor of our class separately. Java Compiler is not going to do that for us.
Now, for further clarity, let's say our no argument constructor happened to call another constructor using this or super keyword
Second(){
this(2); // our default constructor(no argument constructor) is calling another constructor.
}
Output: HelloBlogger
Reason: This time our default constructor is actually calling another constructor, So Java compiler is not going to call super() ****BUT***** Second(int) is implicitly calling it!
The basic rule is that one way or another a superclass constructor is always called
Output: HelloBlogger
Reason: This time our default constructor is actually calling another constructor, So Java compiler is not going to call super() ****BUT***** Second(int) is implicitly calling it!
The basic rule is that one way or another a superclass constructor is always called