- In Java another constructor of the same class can be called from a constructor via this() . Note however that this has to be on the first line. Within a constructor, we can use the this keyword to invoke another constructor in the same class. Doing so is called an explicit constructor invocation.
Constructor Chaining in Java:
- In Java, we can call one constructor from another and it’s known as constructor chaining in Java.
- this and super keyword is used to call one constructor from other in Java.
- this() can be used to call another constructor of same class while super() can be used to call a constructor from super class in Java.
- this() in reality calls no argument constructor of the same class while this(2) calls another constructor of the same class which accepts one integer parameter.
- super() can be used to call no argument constructor of super class and super with parameter can be used to call other overloaded constructors of parent class.
- Calling one constructor from other is called constructor chaining in Java
- Constructor chaining is also used to implement telescoping pattern where an object can be created with combination of multiple property.
Example Program
- In the below example the class “ChainingDemo” has 4 constructors and we are calling one constructor from another using this() statement.
- For e.g. in order to call a constructor with single string argument we have supplied a string in this() statement like this(“hello”).
Note: this() should always be the first statement in constructor otherwise you will get the below error message:
Exception in thread “main” java.lang.Error: Unresolved compilation problem:
- Constructor call must be the first statement in a constructor
Output:
Default constructor
Parametrized constructor with single param
Parametrized constructor with double args
Parametrized constructor with three args
Another example of constructor chaining which shows How to call overloaded constructor of same class and parent class in Java.
[ad type=”banner”]OUTPUT:
Constructor chaining Example in Java
One String argument constructor of Parent called
One argument constructor of Super class called from sub class
———————————
One String argument constructor of Parent called
One argument constructor of Super class called from sub class
No argument constructor of Child called
nice one