This question already has answers here:
Why do I get Infinite loop(Stackoverflow error) while creating an object in a class with constructor? [duplicate]
                                
                                    (4个答案)
                                
                        
                        
                            stackoverflow error in class constructor
                                
                                    (2个答案)
                                
                        
                        
                            Why am I getting a StackOverflowError exception in my constructor
                                
                                    (3个答案)
                                
                        
                6个月前关闭。
            
        

我创建了一个类,一个实例变量在main方法内部创建,另一个在外部方法创建。

// calling a method from constructor
public class Raw4 {

    public static void main(String[] args) {
        Raw4 r = new Raw4();
    }

    Raw4 r1 = new Raw4();

}

最佳答案

创建新的Raw4对象时,所有带有初始化程序的字段都会被初始化。

您的Raw4类具有一个名为'r1'的字段,其类型为Raw4,并通过创建...另一个Raw4对象进行初始化。

因此,创建Raw4对象的操作涉及创建Raw4对象。那是一个永无止境的过程。

关于java - 为什么显示给我java.lang.StackOverflow错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58522763/

10-10 15:50