Constructor chaining is the process where a constructor is called from another constructor. We have to use “this” keyword to achieve the constructor chaining. There is a hard rule that in case of constructor chaining the “this” keyword should always be the first statement.
An Example:
public class Temp
{
Temp() //line #3
{
this(10);
System.out.println("First default constructor.");
}
Temp(int x) //line #8
{
this(10, 20);
System.out.println("Second single parameter constructor. "
+ x);
}
Temp(int x, int y) //line #13
{
System.out.println("Third constructor with 2 parameters " +
x + " & " + y);
}
public static void main(String args[])
{
new Temp();
}
}
In above example the first constructor at line no 3 calls second constructor using “this” keyword, then before executing the statements inside this constructor it goes to the called constructor which is second one. Further second constructor invokes third one in similar way.
Note: Whenever we are achieving constructor chaining using “this”, we must skip “this” in at least one constructor otherwise it will go to infinite execution.
Quick Question – In constructor chaining why we use “this” to call a constructor, can’t we use the constructor name directly?
Answer – No, because if any method exists in class with the class name then compiler will get confused which one to call, the method or the constructor.
Quick Question – why we need constructor chaining?
Answer – when multiple tasks like initialization, database connection, network connectivity etc. then a single constructor will be complex and lengthy and code will be difficult to debug, for this reason we need constructor chaining.
No comments:
Post a Comment