在从构造函数引发未经检查的异常时面临java.lang.StackOverflowerError
我试图运行下面的代码示例,但出现StackOverflow错误。它似乎陷入了无限循环。有人能帮我弄清楚这里发生了什么吗 请查找下面的代码片段在从构造函数引发未经检查的异常时面临java.lang.StackOverflowerError,java,exception,constructor,unchecked-exception,Java,Exception,Constructor,Unchecked Exception,我试图运行下面的代码示例,但出现StackOverflow错误。它似乎陷入了无限循环。有人能帮我弄清楚这里发生了什么吗 请查找下面的代码片段 public class ConstructorExample { private ConstructorExample c1 = new ConstructorExample(); public ConstructorExample(){ throw new RuntimeException(); }
public class ConstructorExample {
private ConstructorExample c1 = new ConstructorExample();
public ConstructorExample(){
throw new RuntimeException();
}
public static void main(String[] str){
ConstructorExample c = new ConstructorExample();
}
}
你有会员吗
私有构造函数示例c1=新构造函数示例();
在ConstructorExample类中
当您实例化ConstructorExample的第一个实例时,JVM会为该ConstructorExample分配内存,然后尝试实例化第一个成员c1。此实例化从为另一个ConstructorExample实例分配内存开始,依此类推
此外,运行时异常与此无关,因为成员初始值设定项是在构造函数之前执行的。。尝试从main方法创建
ConstructorExample
,在调用构造函数之前初始化实例变量
private ConstructorExample c1 = new ConstructorExample();
然后再次重复该循环,继续分配越来越多的内存,导致堆栈溢出,甚至没有完成完全创建单个实例