简体   繁体   English

Java - 在其构造函数中实例化同一类的对象

[英]Java - instantiating objects of same class in its constructor

Why instantiating objects of same class within its constructor throws StackOverflowError ? 为什么在其构造函数中实例化相同类的对象会抛出StackOverflowError For instance , 例如 ,

public class A {
    public A () {
        A a = new A() 
    }
}

will throw StackOverFlowError ? 会抛出StackOverFlowError吗?

It's exactly the same as with any other function unconditionally calling itself with exactly the same parameters: 它与使用完全相同的参数无条件地调用自身的任何其他函数完全相同:

public void f() {
  f(); // <---- will cause a stack overflow due to infinite recursion
}

The function just keeps calling itself, and each invocation requires stack space. 该函数只是自己调用,每次调用都需要堆栈空间。 Sooner or later the stack is exhausted, and you get an exception. 堆栈迟早会耗尽,你会遇到异常。

Exactly the same thing happens when A() keeps calling itself (in new A() ). A()继续调用自身(在new A() )时,会发生完全相同的事情。

Because your new A() statement will call the constructor of the A class, which will call the constructor of the A class, and so on. 因为你的new A()语句将调用A类的构造函数,它将调用A类的构造函数,依此类推。 This creates an infinite recursion. 这会产生无限递归。 THis causes the JVM to throw StackOverflowError s. 这会导致JVM抛出StackOverflowError

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

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