Tuesday, May 3, 2011

Published 5/03/2011 by with 3 comments

recursive constructor invocation

If a constructor calls itself, then the error message "recursive constructor invocation" is shown. It may happen when we overload constructors and call the wrong constructor (itself) accidentally.

See the wrong code below:
public class Employee
{
  private int id;
  private String name;
  public Employee(int id,String name)
  {
    this.id = id;
    this.name = name;
  }
  public Employee(int id)
  {
    this(id); 
    /* this(id) calls the constructor having one parameter of int type. Thus this is calling itself.*/
  }
  public Employee()
  {
  }
}


In the above code, there are three constructors:
i) Employee(int id,String name)
ii) Employee(int id)
iii) Employee()

Within the second constructor, we have written this(id) which means it calls a constructor with one int parameter and see that it is the constructor itself. It means we have not invoked the right constructor. If we want to invoke the first constructor Employee(int id,String name) within the second constructor we should write this(id,null). We are providing null for the String name as no value is available for the name variable in the second constructor but now it calls the first constructor Employee(int id,String name) as we have provided  two parameters now.

See the corrected code below:

public class Employee
{
  private int id;
  private String name;
  public Employee(int id,String name)
  {
    this.id = id;
    this.name = name;
  }
  public Employee(int id)
  {
    this(id,null); // this(id,null) calls another constructor having two parameters
  }
  public Employee()
  {
  }
}

Summary:

If you see the error message "recursive constructor invocation", check that you have provided correct no and type of parameters while calling one constructor in another one.
    email this       edit

3 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Nice article , you have indeed covered topic in details with sample code and graphics, its indeed a topic which require a deeper understanding than many other java topics.

    Javin
    Difference between ConcurrentHashMap , Hashtable and SynchronizedMap

    ReplyDelete
  3. public class Employee
    {
    private int id;
    private String name;
    public Employee(int id,String name)
    {
    this.id = id;
    this.name = name;
    }
    public Employee(int id)
    {
    this(id,null); // this(id,null) calls another constructor having two parameters
    }
    public Employee()
    {
    }
    }

    Is Correct
    http://tehapps.com/

    ReplyDelete