簡體   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