2017-03-20 75 views
-1
public class Test { 
    Test t = new Test(); 
    public static void main(String[] args) { 
    Test t1 = new Test(); 
    } 
} 
+8

因为测试实例测试()! –

回答

1

因为该行:

Test t = new Test(); 

将产生无穷的递归实例化。

2

这是因为每当Test创建新对象,将重新创建一个对象t,同时将重新初始化......这样下去

public class Test { 
    Test t = new Test(); //-> recursive instantiation 
    public static void main(String[] args) { 
     Test t1 = new Test(); 
    } 
} 

尝试删除Test t = new Test();或使其静态static Test t = new Test();,它应该解决您的问题。

public class Test { 
    static Test t = new Test(); //or remove it 
    public static void main(String[] args) { 
     Test t1 = new Test(); 
    } 
} 
4

你的代码有没有构造,这是编译器做什么 -

public class Test { 
    Test t; // <-- initializer copied to every constructor body, even the default. 
    public Test() { // <-- compiler adds default constructor, 
    super(); 
    t = new Test(); //<-- infinite recursion. 
    } 
    public static void main(String[] args) { 
    Test t1 = new Test(); // <-- invokes default constructor 
    } 
}