Bootstrap

奇特的java类

public class Test {
	
	private Test(){}
	
	public Test instance = new Test();
	
	public static Test custon(){
		return new Test();
	}
	
	public static void main(String[] args) {
		Test.custon();
	}

}

运行结果比较特别

Exception in thread "main" java.lang.StackOverflowError
	at Test.<init>(Test.java:5)
	at Test.<init>(Test.java:5)
	at Test.<init>(Test.java:5)
	at Test.<init>(Test.java:5)
	at Test.<init>(Test.java:5)
	at Test.<init>(Test.java:5)
	at Test.<init>(Test.java:5)
	at Test.<init>(Test.java:5)
	at Test.<init>(Test.java:5)
	at Test.<init>(Test.java:5)

之所以会报错,是由于new Test对象的时候,会先对成员变量初始化,成员变量instance初始化的过程是new Test对象,而new Test对象,又需要初始化instance,所以导致了死循环,最后抛出了StackOverflowError。

;