![]() |
VOOZH | about |
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:
Example
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.
Example:
Output:
👁 ImageNow 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.
Implementation:
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:
Example: