您查看的文章来源于http://www.oklinux.cn
读者先来看看下面两段代码执行结果有什么不同?
片段一:
public Test() {
System.out.println("start");
System.out.println((new Integer(10)).toString());
Test t = new Test(); //第5行
System.out.println("end");
excute("Why I am right ?"); //第7行
}
public void excute(String msg) {
System.out.println(msg);
}
public static void main(String[] args) {
new Test();
}
}
片段二: 将第5行, 即 "Test t = new Test();" 注释掉.
运行结果:
片段一的结果为:
start
10
start
10
...
Exception in thread "main" java.lang.StackOverflowError
片段二的结果为:
start
10
end
Why I am right ?
为什么呢?
因为对象的创建入口是 构造函数, 构造函数会递规地"初始化"构造函数中声明的对象, 所以出现了其递规地调用自己的情况,, 直到耗尽stack.
细心的读者可能注重到第7行能真确地执行, 为什么呢, 留给读者思考了...希望这篇文章能给初学者有所帮助.