Recursive Constructor Invocation in Java
The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. In the recursive program, the solution to the base case is provided and the solution of the bigger problem is expressed in terms of smaller problems. Here recursive constructor invocation and stack overflow error in java. It is as shown below in the example as follows:
Call 1 Call 2 Call 3 Call 4 Call 5
Recursive Constructor Invocation
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.
Now let us discuss what exactly we do refer to by Stack overflow error and why does it occur. Stack overflow error occurs if we do not provide the proper terminating condition to our recursive function or template, which means it will turn into an infinite loop.
Here we have created a GFG object inside the constructor which is initialized by calling the constructor, which then creates another GFG object which is again initialized by calling the constructor and it goes on until the stack overflows. This can be justified from the illustration as follows:
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.