[英]Why does the java code below give StackOverflow error?
I am getting StackOverflow error while executing the below: 执行以下命令时出现StackOverflow错误:
public class StackOverflow7 {
StackOverflow7 obj = new StackOverflow7();
int finalCount = 0;
public static void main(String[] args) {
for(int i = 1 ; i <= 5 ; i++)
System.out.println(i);
StackOverflow7 localObj = new StackOverflow7();
localObj.count(88);
System.out.println("Final Count :: " + localObj.finalCount);
}
private void count(int num){
finalCount = finalCount + num;
}
}
This line: 这行:
StackOverflow7 obj = new StackOverflow7();
is always called when you create an object of StackOverflow7
, which you are doing in this line itself. 当您创建
StackOverflow7
的对象时, 总是会调用,这是您在此行本身中所做的。 Thus, this line recursively calls itself, until you get a StackOverflow error. 因此,此行将递归调用自身,直到出现StackOverflow错误。
You get the stack overflow because of this line: StackOverflow7 obj = new StackOverflow7();
由于此行而导致堆栈溢出:
StackOverflow7 obj = new StackOverflow7();
. 。 Whenever you create a new instance, it is called and thus you create a new instance and create a new instance and so on.
每当您创建新实例时,都会调用它,因此您将创建一个新实例并创建一个新实例,依此类推。 In your stack trace you should thus see a lot of
<clinit>
lines. 因此,在堆栈跟踪中,您应该看到很多
<clinit>
行。
You start the whole thing by calling StackOverflow7 localObj = new StackOverflow7();
您可以通过调用
StackOverflow7 localObj = new StackOverflow7();
开始整个操作StackOverflow7 localObj = new StackOverflow7();
in your main method. 在您的主要方法中。
To fix this either make obj
a static field or remove it altogether, since you're not using it anyways. 要解决此问题,请将
obj
静态字段,或者将其全部删除,因为无论如何您都不会使用它。
Because of this line: 由于这一行:
StackOverflow7 obj = new StackOverflow7();
Every time you create a new object this line will executet and try to create an other object 每次创建新对象时,该行都会执行并尝试创建另一个对象
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.