Tuesday, 7 August 2018

SE - 32 - Can we have Constructors inside constructor(or constructor chaining)

Yes we can have multiple constructors a class with different signatures. Also we can call the constructor from the constructor using this keyword :

See the example below :

public class ConstInConst {
// constructor 1
 ConstInConst(){
  this(1,2); //calling constructor 2
 }
//constructor 2
 ConstInConst(int i, int j) {
 this(4,5,6); // calling constructor 3
 System.out.println(i +" and "+ j);
 }
//constructor 3
 ConstInConst(int i, int j, int k) {
 System.out.println(i +" and "+ j + " and " + k);
 }

 public static void main(String[] args) {
  new ConstInConst();
 }
}
Output : 
4 and 5 and 6
1 and 2


In the above example we have created 3 constructors and called the second constructor in first and third in second. This term is also called constructor chaining. We can't call 2 constructors in a single constructor(only one is allowed at a time) . It gives error because the first line should call the constructor. 



No comments:

Post a Comment