简体   繁体   English

java.lang.StackOverflowError?

[英]java.lang.StackOverflowError?

I am sure that, this ques code must be asked in this site. 我敢肯定,此问题代码必须在此站点中询问。 But I am not able to search, This is basic ques, but I am not getting it because of my poor basic concept- 但是我无法搜索,这是基本问题,但是由于我的基本概念较差,我无法获取它-

public class A {

A obj = new A();

public static void main(String arg[])
{
    A ob = new A();
}
} 

It is giving java.lang.StackOverflowError ,Why? 它给java.lang.StackOverflowError ,为什么?

每次创建对象A ,都会创建另一个对象A ,该对象也将创建另一个对象A ...

Your class is essentially equivalent to: 您的课程基本上等于:

public class A {

    A obj;
    public A() {
        obj = new A();
    }  

    public static void main(String arg[]) {
        A ob = new A();
    }
}

Now you see how you got that error? 现在您知道如何得到该错误了? Everytime you create an instance of A , the constructor get's called, which again invokes itself to create another instance, and this goes on filling up the stack till it overflows. 每次创建A的实例时,构造函数get都会被调用,它再次调用自身来创建另一个实例,然后继续填充堆栈直到溢出。

StackOverflow errors occur because there is a very deep recursion within the application. 发生StackOverflow错误是因为应用程序内部存在非常深的递归。 When you instantiate A , you also call the same constructor to create another instance of A and hence, you have a recursive tree and thus causing the stack overflow error. 实例化A ,您还调用相同的构造函数来创建A另一个实例,因此,您具有递归树,从而导致堆栈溢出错误。

Hence, the real problem is deep recursive calls to instantiate A . 因此,真正的问题是实例化A深度递归调用。

当创建类型为A的对象时,您正在创建类型为A的新对象,这将创建类型为A的新对象,等等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM