问题描述
这是我的代码:
public class ConstructorsDemo{
public static void main(String a[]){
Cons1 c1 = new Cons1();
}
}
class Cons1{
Cons1 c = new Cons1();// the error is in this line
Cons1(){
//does somwthing
}
}
所以我在这里收到一个无限循环错误(Stackoverflow).但是,如果我注释掉我创建的两个对象中的任何一个,也没关系.
So I get an infinite loop error here (Stackoverflow).However it's fine if I comment out any of the two objects I have created.
我的代码中的对象 c
如何导致Stackoverflow错误?
How is the object c
in my code causing Stackoverflow error?
推荐答案
第一点:这是无限递归,不是是无限循环.有很大的不同.有绝对合理的理由使用无限循环,并且它们通常不会导致堆栈溢出异常.但是,没有 个合法的用例可用于无限递归,并且其使用将总是会导致堆栈溢出异常.(我想您可能会在有些奇怪的情况下为具有但仍然存在的语言争取无限的尾递归.)如果您遇到堆栈溢出异常,则几乎可以肯定是无限递归,而不是无限循环.
First point: this is infinite recursion, not an infinite loop. There's a big difference. There are perfectly legitimate reasons to use infinite loops and they will not, in general, cause stack overflow exceptions. However, there are no legitimate use cases for infinite recursion and its use will invariably lead to a stack overflow exception. (I suppose you could maybe argue for infinite tail recursion in a few odd situations for languages that have that but still...) If you get a stack overflow exception, it's almost certainly infinite recursion rather than an infinite loop.
正如其他人指出的,这里的基本问题是,每次您调用新"时,它都会创建一个新对象,然后又创建一个新对象,依此类推.
The basic problem here, as others have pointed out, is that every time you call "new" it, in turn, creates a new object, which in turn creates a new object, and so on and so forth.
Cons1 c = new Cons1();
这篇关于为什么在使用构造函数的类中创建对象时出现无限循环(Stackoverflow错误)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!