[英]Why am i facing this and what is workflow
任何人都可以在下面的代码中帮助理解运行时的StackOverFlowError。 我无法理解工作流程。 其中一个采访问题:)
public class Interview {
Interview i1 = new Interview();
Interview(){
System.out.println("Hello");
}
public static void main(String[] args){
Interview i = new Interview();
}
}
您的构造函数正在初始化自己。 这是你的构造函数对JVM的看法:
Interview i1;
Interview(){
super();
i1 = new Interview(); // this line calls the constructor
System.out.println("Hello");
}
你的Interview i1 = new Interview();
说每个Interview
都有自己的 Interview
对象属于它,所以一旦你在main
调用new Interview()
,系统就开始尝试为那个创建一个新的Interview
,并为那个Interview
新的Interview
......
它甚至从未进入(显式)构造函数,因为系统首先在一个永无止境的新Interview
链上运行。 您几乎肯定会从Interview
类中删除i1
字段。
您正在创建一个新的Interview
每次实例化一个时间Interview
。 这导致构造函数调用和实例化的永无止境的循环,最终耗尽您的堆栈空间(因为函数调用占用堆栈空间)。
请注意,如果您有可用的无限堆栈空间,则最终会从堆上分配的所有Interview
对象失败。
因为一旦你在main()
初始化第一个Interview()
,它就会创建并初始化第二个Interview
,它会创建并初始化另一个,等等。
您在字段中执行的所有初始化都将成为无参数构造函数的一部分(在您的情况下)。
所以,你的代码就会变成
public class Interview
{
Interview i1;
Interview()
{
super();//by default calls the constructor of Object
i1 = new Interview();//initialization becomes part of constructor
System.out.println("Hello");
}
}
现在,这会以递归方式实现Interview导致异常
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.