[英]Why am i facing this and what is workflow
Could anyone please help in understanding the StackOverFlowError at runtime in below code. 任何人都可以在下面的代码中帮助理解运行时的StackOverFlowError。 I am not able to understand workflow.
我无法理解工作流程。 One of the interview Question:)
其中一个采访问题:)
public class Interview {
Interview i1 = new Interview();
Interview(){
System.out.println("Hello");
}
public static void main(String[] args){
Interview i = new Interview();
}
}
Your constructor is initializing itself. 您的构造函数正在初始化自己。 This is what your constructor looks like to the JVM:
这是你的构造函数对JVM的看法:
Interview i1;
Interview(){
super();
i1 = new Interview(); // this line calls the constructor
System.out.println("Hello");
}
Your Interview i1 = new Interview();
你的
Interview i1 = new Interview();
says that each Interview
has its own Interview
object that belongs to it, and so once you call new Interview()
in main
, the system starts trying to create a new Interview
for that one, and a new Interview
for that one... 说每个
Interview
都有自己的 Interview
对象属于它,所以一旦你在main
调用new Interview()
,系统就开始尝试为那个创建一个新的Interview
,并为那个Interview
新的Interview
......
It never even makes it to the (explicit) constructor, because the system goes off on a never-ending chain of new Interview
s first. 它甚至从未进入(显式)构造函数,因为系统首先在一个永无止境的新
Interview
链上运行。 You should almost certainly remove the i1
field from the Interview
class. 您几乎肯定会从
Interview
类中删除i1
字段。
You're creating a new Interview
every time you instantiate an Interview
. 您正在创建一个新的
Interview
每次实例化一个时间Interview
。 This leads to a never-ending cycle of constructor calls and instantiations, which eventually run out your stack space (because the function calls take stack space). 这导致构造函数调用和实例化的永无止境的循环,最终耗尽您的堆栈空间(因为函数调用占用堆栈空间)。
Note that if you had infinite stack space available to you, you would eventually fail from all the Interview
objects being allocated on the heap. 请注意,如果您有可用的无限堆栈空间,则最终会从堆上分配的所有
Interview
对象失败。
因为一旦你在main()
初始化第一个Interview()
,它就会创建并初始化第二个Interview
,它会创建并初始化另一个,等等。
All initialization you do at the fields would become the part of the parameter-less constructor(in your case). 您在字段中执行的所有初始化都将成为无参数构造函数的一部分(在您的情况下)。
So,your code would become 所以,你的代码就会变成
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");
}
}
Now this would recursively instatiate Interview causing exception 现在,这会以递归方式实现Interview导致异常
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.