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

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

问题描述

请帮助理解为什么以下代码

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 ?

- edit--
对于指出的重复项,我确实理解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:递归构造函数调用和stackoverflow错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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