- Calling a constructor from another constructor , is known as constructor chaining.If we want to access the properties of any constructor then we have to use constructor chaining.
- We know that constructor is neither static nor non static. So we can’t inherit the constructor.But using constructor chaining we can acquire the properties of another constructor.
- There is two ways to achieve the constructor chaining:-
2.) this() (call to this) is used to call the same class constructor. That mean we can achieve the properties of constructor which are present in the same class. For using this() constructor overloading is necessary. Without constructor overloading we can’t get the properties of same class.
Examples :-
Step 1.)
class Temp
{
Temp() //default constructor
{
this(10);
System.out.println("default constructor");
}
Temp(int x) //one parameter constructor
{
this(10,20);
System.out.println("value of x is" +x);
}
Temp(int x,int y) //two parameter constructor
{
System.out.println("Add result is" +(x+y));
}
public static void main(String[] args)
{
new Temp();
}
}
Explanation of Program:- The class Temp contains three constructors: default constructor, one parameter constructor and two parameter constructor.
- The statement : new Temp(); calls a default constructor. Here it calls the one parameter constructor with the help of this(10);
- Then control goes to two parameter constructor with the help of first statement in constructor this(10,20),
- In two parameter constructor the first statement will be executed which prints the “add result is 30”
- Then control goes to one parameter constructor and it executes the second statement which prints “value of x is 10”
- Then control goes to default constructor and it also execute the second statement that prints “default constructor”
Important Points to Remember About Constructor Chaining:
- Whenever you are achieving a constructor chaining using a this() method then it must be the first line in any constructor.
- Whenever we are achieving a constructor chaining using a this() method then there must be atleast one constructor which is not having a this() method as a first line.
- Constructor chaining can be achieved in any order.
- Whenever you want to provide the certain common resources to each object of a class rather than putting the code of each resource in a single constructor, make a separate constructor for each resource and then create their chain.
No comments:
Post a Comment