打字猴:1.70044117e+09
1700441170
1700441171 public class Client{
1700441172
1700441173 public static void main(String[]args){
1700441174
1700441175 Son s=new Son();
1700441176
1700441177 s.doSomething();
1700441178
1700441179 }
1700441180
1700441181 }
1700441182
1700441183 //父类
1700441184
1700441185 class Father{
1700441186
1700441187 Father(){
1700441188
1700441189 new Other();
1700441190
1700441191 }
1700441192
1700441193 }//子类
1700441194
1700441195 class Son extends Father{
1700441196
1700441197 public void doSomething(){
1700441198
1700441199 System.out.println(“Hi, show me something”);
1700441200
1700441201 }
1700441202
1700441203 }
1700441204
1700441205 //相关类
1700441206
1700441207 class Other{
1700441208
1700441209 public Other(){
1700441210
1700441211 new Son();
1700441212
1700441213 }
1700441214
1700441215 }
1700441216
1700441217 这段代码并不复杂,只是在构造函数中初始化了其他类,想想看这段代码的运行结果是什么?是打印“Hi, show me something”吗?
1700441218
1700441219 答案是这段代码不能运行,报StackOverflowError异常,栈(Stack)内存溢出。这是因为声明s变量时,调用了Son的无参构造函数,JVM又默认调用了父类Father的无参构造函数,接着Father类又初始化了Other类,而Other类又调用了Son类,于是一个死循环就诞生了,直到栈内存被消耗完毕为止。
[ 上一页 ]  [ :1.70044117e+09 ]  [ 下一页 ]