Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor calling itself

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?

like image 228
Pyae Phyo Aung Avatar asked Mar 29 '12 03:03

Pyae Phyo Aung


People also ask

Can a constructor call itself in Java?

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.

What is constructor calling?

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.

What is recursive invocation?

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.

Can we call a constructor multiple times?

Constructors are called only once at the time of the creation of the object.


2 Answers

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.

like image 146
Piyush-Ask Any Difference Avatar answered Sep 27 '22 19:09

Piyush-Ask Any Difference


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.

like image 33
PVR Avatar answered Sep 27 '22 20:09

PVR