Constructor overloading in Java
In Java, we can overload constructors like methods. The constructor overloading can be defined as the concept of having more than one constructor with different parameters so that every constructor can perform a different task.
Consider the following Java program, in which we have used different constructors in the class.
this a default constructor Default Constructor values: Student Id : 0 Student Name : null Parameterized Constructor values: Student Id : 10 Student Name : David
In the above example, the Student class constructor is overloaded with two different constructors, I.e., default and parameterized.
Here, we need to understand the purpose of constructor overloading. Sometimes, we need to use multiple constructors to initialize the different values of the class.
We must also notice that the java compiler invokes a default constructor when we do not use any constructor in the class. However, the default constructor is not invoked if we have used any constructor in the class, whether it is default or parameterized. In this case, the java compiler throws an exception saying the constructor is undefined.
Consider the following example, which contains the error since the Colleges object can't be created using the default constructor now since it doesn't contain one.
Use of this () in constructor overloading
However, we can use this keyword inside the constructor, which can be used to invoke the other constructor of the same class.
Consider the following example to understand the use of this keyword in constructor overloading.
Printing Student Information: Name: John Id: 101 Contact No.: 9899234455 College Name: 9899234455 Passing Year: 2018
Next TopicControl Flow in Java