为什么不能在构造函数中实例化该类的相同对象? [英] Why can't you instantiate the same object of that class inside constructor?

查看:117
本文介绍了为什么不能在构造函数中实例化该类的相同对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class Run{
 public static void main(String... args){
      A a1 = new A();
 }
}

class A{
  public A(){
    A a = new A();
  }
  //here as well A a = new A();
}

为什么这会给出 java.lang.StackOverflowError ?在这里发生递归呼叫吗?它是如何发生的?

Why does this give a java.lang.StackOverflowError? Is there a recursive call happening here? How does it happen?

推荐答案

你可以调用,但这将是一个无限运行的递归调用。这就是你得到 StackOverflowError 的原因。

You can call, but it would be a recursive calling which will run infinitely. That's why you got the StackOverflowError.

以下内容完美无缺:

public class Run{

 static int x = 1;
 public static void main(String... args){
      A a1 = new A();
 }
}

class A{
   public A(){
     if(x==1){
        A a = new A();
        x++;
    }
  }
}

这篇关于为什么不能在构造函数中实例化该类的相同对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆