Constructor Chaining and Constructor Overloading in Java
Constructor Chaining
Constructor chaining and constructor overloading are two confusing terms. Let's first understand constructor chaining.
Constructor chaining is the process of calling one constructor from another constructor using the same object. To call the constructor, we use either this or super keyword. 'this' keyword is used in the case when a call is made from the same class whereas 'super' keyword is used in a case when a call is made for the super i.e. parent class constructor.
A constructor can be called explicitly or automatically. this () and this (parameter) is used for calling same class non-parameterized and parameterized constructor respectively. Similarly super () and super (parameter) is used for calling parameterized and non-parameterized constructor of the superclass.
Why constructor chaining is needed
In order to perform multiple tasks within the same constructor, rather than using a separate constructor for each task, constructor chaining is used. It makes the program more readable.
Example:
public class A
{
public A()
{
System.out. println ("this is non parameterized constructor of A class");
}
public A(String name)
{
System.out.println ("this is parameterized constructor of A class called by"+name);
}
}
class B extends A
{
public B()
{
this(" javatpoint ");
System.out.println ("this is non parameterized constructor of child class");
}
public B(String string)
{
super ("javatpoint");
System.out.println ("this is parameterized constructor of child class");
}
public static void main(String args[])
{
B b = new B ();
}
}
Output:
this is parameterized constructor of A class called by javatpoint. this is parameterized constructor of child class. this is non-parameterized constructor of child class.
Constructor Overloading
As methods are overloaded in Java, in the same way, constructors can also be overloaded. Constructor overloading is having more than one constructor within different parameters lists. Then the question is how the compiler will distinguish b/w them? Actually, Compiler can distinguish b/w these constructors with the help of parameters and data types.
Example:
class Employee
{
int eid;
String name;
long phoneno ;
public Employee(int x, String y, long z) {
eid =x;
name = y;
phoneno=z;
}
public Employee(int a, String b) {
eid = a;
name = b;
}
void show()
{
System.out.println (eid+" "+name+" "+phoneno);
}
public static void main(String args[])
{
Employee e1 = new Employee(123,"Rahul");
Employee e2 = new Employee(231," Shikha ", 3789329);
e1.show ();
e2.show ();
}
}
Hence the constructor overloading and constructor chaining are the two different concepts. The above mentioned example will help you to understand them in better way.