javascript
Brief description  about Online courses   join in Online courses
View Arun Kumar Das 's Profile

Constructor Chaining with example

Calling a constructor from the another constructor of same class is known as Constructor chaining.

We will understand this with the help of below program.


Example:-

In the below example the class “Chaining_Ex” has 4 constructors and we are calling one constructor from another using this() statement.

For example 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


package SI_Ar.com;

public class Chaining_Ex {

//default constructor of the class

public Chaining_Ex(){
System.out.println("Default constructor");
}
public Chaining_Ex(String str){
this();
System.out.println("Parametrized constructor with single param");
}
public Chaining_Ex(String str, int num){
//It will call the constructor with String argument
this("Hello");
System.out.println("Parametrized constructor with double args");
}
public Chaining_Ex(int num1, int num2, int num3){
// It will call the constructor with (String, integer) arguments

this("Hello", 3);
System.out.println("Parametrized constructor with three args");
}
public static void main(String args[]){
//Creating an object using Constructor with 3 int arguments
Chaining_Ex obj = new Chaining_Ex(3,3,12);
}
}

Output:

Default constructor
Parametrized constructor with single param
Parametrized constructor with double args
Parametrized constructor with three args
Asked by Arun Kumar Das | Dec 30, 2014 |  Reply now
Replies (0)