以下Java程序出现了堆栈溢出错误

3
public class testing {    
    testing t=new testing();                

    public static void main(String args[]){   
        testing t1=new testing();  
        t1.fun();  
    }

    void fun(){         
        int a=2;        
        int b=t.fun2(a);  
        System.out.println(a+" "+b);  
    }

    int fun2(int a)  
    {
        a=3;  
        return a;  
    }  
}

为什么上面的代码会出现以下错误?我只是想知道原因,因为在这种情况下很难预料到StackOverFlowError错误。
Exception in thread "main" java.lang.StackOverflowError
at com.testing.<init>(testing.java:4)
at com.testing.<init>(testing.java:4)

1
啊,请缩进你的代码。当你的代码可读性更好时,我们帮助你会更容易些。 - Jack Satriano
1
另外,类名应该大写。查阅一些代码风格指南。 - Jack Satriano
1
@jack57 我知道编码规范,只是为了快速测试而编写了代码。不过还是谢谢你的建议。 - user980089
有人能提供一个链接吗?我想了解更多,因为我还有一些疑问。 - user980089
3个回答

13
您正在递归创建testing的实例。
public class testing {    
 testing t=new testing();        
//

}

创建第一个实例时,它将通过 testing t = new testing(); 创建新实例,这将再次创建新实例,以此类推。


1
我为测试类创建了对象,根据我的理解它只会被创建一次。你能解释一下如何创建多个实例吗? - user980089
1
在创建第一个实例时,通过 testing t = new testing(); 创建新实例,这将再次创建新实例,如此往复。 - jmj
1
当您第一次创建new testing()时,它将创建该类的一个对象,但是该类具有new testing()并且创建该对象,然后它将继续...... - Karesh A
@JigarJoshi 我仍然不明白为什么 public class testing { testing t=new testing(); public static void main(String args[]){ System.Out.Print("hello");}} 可以成功运行。 - user980089
2
@user980089 发生的情况是你实例化了一个 testing 对象,第一件事就是这个对象运行了它的所有字段初始化器。在你的情况下,唯一的初始化器是 testing t = new testing(),所以它运行了。那么,这是什么意思呢?它实例化了一个 testing 对象,这意味着它的所有字段都被初始化了——即它的 testing t = new testing()。依此类推。但如果没有第一个 new testing() 来启动这些东西,它们中的任何一个都不会运行——因为 testing t 是一个实例变量,而不是静态变量,因此只适用于新实例。 - yshavit
显示剩余5条评论

1

请尝试这个解决方案,

public class testing {                

    public static void main(String args[]){   
        testing t1=new testing();  
        t1.fun(t1);  
    }

    void fun(testing t1){         
        int a=2;        
        int b=t1.fun2(a);  
        System.out.println(a+" "+b);  
    }

    int fun2(int a)  
    {
        a=3;  
        return a;  
    }  
}

谢谢Kushan提供的解决方案,但我只是想知道出错的原因。 - user980089

1

你需要在类级别创建字段,但在主函数中只实例化一次。

public class Testing {    
    static Testing t1;              

    public static void main(String args[]){   
        t1=new Testing();  
        t1.fun();  
    }

    void fun(){         
        int a=2;        
        int b=t1.fun2(a);  
        System.out.println(a+" "+b);  
    }

    int fun2(int a)  
    {
        a=3;  
        return a;  
    }  
}

还有一些替代方案可以避免这个问题。 - RTA

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接