2017-07-29 17 views
2

任何人都可以告诉我为什么这个工程?任务是添加最低限度的静态关键字以使此代码有效。静态与method1和method2我可以理解,但为什么把它添加到int步?为什么这段代码有效?任务添加静态关键字

/* Minimum number of static keywords 
Add the minimum number of static keywords to make the code compile and the program to successfully complete. 
*/ 

public class Solution { 
    public static int step; //static was added here 

    public static void main(String[] args) { 
     method1(); 
    } 

    public static void method1() { //static was added here 
     method2(); 
    } 


    public static void method2() { //static was added here 
     new Solution().method3(); 
    } 

    public void method3() { 
     method4(); 
    } 

    public void method4() { 
     step++; 
     for (StackTraceElement element : Thread.currentThread().getStackTrace()) 
      System.out.println(element); 
     if (step > 1) return; 
     main(null); 
    } 
} 
+3

哇多么可怕的代码示例。谁对你造成了这种情况? –

+0

不需要*编译*,但需要使其终止......但是作为T.J.克劳德说,这是非常可怕的。 –

+0

可怕的原因是什么?这只是来自java培训课程的一些任务 – genek

回答

2

因为如果step不是一成不变的,它会具体到method2创建的对象,而且将永远开出0和已增加后成为1,和1 > 1是假的,所以我们不会在再次致电main之前返回。所以这个程序会无休止地缓存(好吧,直到它溢出堆栈才会有)。

相关问题