I have recently found out that no argument constructor and multiple argument constructor cannnot call each other in turns. What is the underlying reason of this limitation? Some might say that constructors are where resources are initialised. So they must not be called recursively. I want to know if this is the only reason or not. Functions/methods/procedures can be called recursively. Why not constructors?
If a constructor calls itself, then the error message “recursive constructor invocation” occurs. The following program is not allowed by the compiler because inside the constructor we tried to call the same constructor. The compiler detects it instantly and throws an error.
The constructor is called when an object of a class is created. It can be used to set initial values for object attributes. In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created.
A recursive call is one where procedure A calls itself or calls procedure B which then calls procedure A again. Each recursive call causes a new invocation of the procedure to be placed on the call stack.
Constructors are called only once at the time of the creation of the object.
The answer lies in the fact that the call to another constructor is the first line of any constructor and hence your if condition to break out of recursion will never be executed and hence stack overflow.
The main purpose of the constructor is to initialize all the global variables described in a particular class.
For Example:
public class Addition(){
int value1;
int value2;
public Addition(){ // default constructor
a=10;
b=10;
}
public Addition(int a, int b){
this(); // constructors having parameters , overloaded constructor
value1=a;
value2=b;
}
}
public class Main(){
public static void main(){
Addition addition = new Addition(); //or
Addition addition = new Addition(15,15);
}
}
Here, if you want to make instance of the class you can either make instance by calling default constructor or by calling constructor having parameters. So the constructors are overloaded and not overridden. If you want to call another constructor, that can only be done be putting either this()
or super()
in the first line of the constructor. But this is not prefferable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With