Java:递归构造函数调用和堆栈溢出错误 [英] Java : recursive constructor call and stackoverflow error

查看:45
本文介绍了Java:递归构造函数调用和堆栈溢出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助理解为什么下面的代码

Please help to understand why does the following code

public class HeapQn1 {

    /**
     * @param args
     */
    public HeapQn1() {
        new HeapQn1();
    }

    static HeapQn1 n = new HeapQn1();

    public static void main(String[] args) {

    }

}

结果

java.lang.StackOverflowError
    at com.rg.test.interview.HeapQn1.<init>(HeapQn1.java:8)
    at com.rg.test.interview.HeapQn1.<init>(HeapQn1.java:9)
    ...

根据我的理解,对象的内存分配发生在堆内存中,我预计会出现 OutOfMemoryError,因为在某些时候堆内存会因为重复创建对象而被填满.

As per my understanding the memory allocation for an object happens in the heap memory and I was expecting an OutOfMemoryError as at some point the heap memory will be full because of repetitive object creation.

在研究中,我发现 java 构造函数被认为是一种方法,并且解释了 StackOverflowError ,直到我阅读了以下线程.

On research , I came across that a java constructor is considered a method and that explained the StackOverflowError , until I read the following thread.

Java 中何时调用构造函数?

说的是

3. The object is fully constructed/created when the constructor returns.

据我所知,构造函数是一种方法,由于堆内存比堆栈内存大得多,递归构造函数调用导致 StackOverflowError .这是正确的吗?

From what I could gather , the constructor is a method and since the heap memory is much larger than stack memory , the recursive constructor call resulted in StackOverflowError . Is this correct ?

既然给定代码中的任何对象都不会被完全创建,那么构造函数的堆栈帧分配是否真的会发生?

Since no object in the give code will get completely created , will stack frame allocation for constructor actually happen ?

--编辑--对于指出的重复项,我确实了解 StackoverflowError 是什么.我在问题在研究中,我发现 java 构造函数被认为是一种方法并且解释了 StackOverflowError".我的问题是了解构造函数是否像其他方法一样获得分配的堆栈帧,因为在构造函数返回之前对象创建尚未完成.希望这能澄清.

--edit-- For the duplicates pointed out , I do understand what StackoverflowError is . I have mentioned in the question "On research , I came across that a java constructor is considered a method and that explained the StackOverflowError". My question is to understand if a constructor gets a stack frame allocated just like other methods as the object creation is not complete until the constructor returns. Hope this clarifies.

推荐答案

每当构造函数被调用时,它的返回地址被推送到堆栈.由于堆栈是有限的且小于堆内存,因此您会收到类似 StackOverflowError 而不是 OutOfMemoryError 的错误.

Whenever the constructor is called, its return address is pushed onto the stack. As the stack is finite and smaller than the heap memory, you are getting error like StackOverflowError rather than OutOfMemoryError.

构造函数是一个方法,由于堆内存比栈内存大很多,递归构造函数调用导致了StackOverflowError.这是正确的吗?

The constructor is a method and since the heap memory is much larger than the stack memory, the recursive constructor call resulted in StackOverflowError. Is this correct ?

是的,您的疯狂猜测是完全正确的.干杯!

Yeah, your wild guess is completely correct. Cheers!

这篇关于Java:递归构造函数调用和堆栈溢出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆