java 无限递归的构造器实例详解

作者:袖梨 2022-11-14

在一些情况下,程序可导致构造器进行无限递归,如:

public class ConstrucorRecursion {
{
ConstrucorRecursion rc = new ConstrucorRecursion();
}
public ConstrucorRecursion()
{
System.out.println("程序执行无参数的构造器");
}
public static void main(String[] args)
{
ConstrucorRecursion rc = new ConstrucorRecursion();
}
}






public class InstanceTest
{
  private String name;
  //持有当前类的实例
  private InstanceTest instance;
  //定义一个无参数的构造器
  public InstanceTest()
  {
   }
  //定义有参数的构造器
  public InstanceTest(String name)
  {
    //调用无参数的构造器初始化intance实例
    instance = new InstanceTest();
    instance.name = name;
  }
  //重写toString()方法
  public String toString()
  {
   return "InstanceTest[instance="+ instance + "]";
   }
  public static void main(String[] args) 
  {
   InstanceTest in = new InstanceTest();
   InstanceTest in2 = new InstanceTest("测试name");
   //让两个对象相互引用
   in.instance = in2;
   in2.instance = in;
   System.out.println(in);
   System.out.println(in2);
  }
}

相关文章

精彩推荐