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:
Example
Java
public class GFG {
static int count = 0 ;
static void function()
{
count = count + 1 ;
if (count <= 5 ) {
System.out.println( "Call " + count);
function();
}
}
public static void main(String[] args) { function(); }
}
|
Output
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:
Java
class GFG {
GFG()
{
this ();
}
public static void main(String[] args)
{
GFG obj = new GFG();
}
}
|
Output:
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.
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:
Java
public class GFG {
GFG()
{
GFG obj1 = new GFG();
}
public static void main(String[] args)
{
GFG obj = new GFG();
}
}
|
Output:
Last Updated :
26 Sep, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...