繁体   English   中英

以下java程序中的stackoverflow错误

[英]stackoverflow error in following java program

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)

您以递归方式创建testing实例

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

}

在创建第一个实例时,它将通过testing t=new testing();来创建新的实例testing t=new testing(); 这将再次创建新实例等

试试这个解决方案

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;  
    }  
}

您必须在类级别创建字段,但在main中将其实例化一次

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;  
    }  
}

暂无
暂无

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

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