今天分析一道經典的構造器遞歸調用題目,揭示物件初始化過程中隱藏的堆疊溢位風險。
public class Ques1117 {
public static void main(String[] args) {
Sub sub = new Sub();
sub.doThing();
}
}
class Parent {
Parent() { new Other(); }
}
class Sub extends Parent {
public void doThing() { System.out.println("Sub doThing..."); }
}
class Other {
public Other() { new Sub(); }
}
main 執行 new Sub()Sub 無顯式構造器,隱式調用 super() → Parent()Parent() 執行 new Other()Other() 執行 new Sub() → 回到步驟 1形成無限遞歸:Sub → Parent → Other → Sub → ...
Exception in thread "main" java.lang.StackOverflowError
at Parent.(Ques1117.java:...)
at Sub.(Ques1117.java:...)
at Other.(Ques1117.java:...)
at Parent.(Ques1117.java:...)
...
Sub doThing... 永遠不會輸出,因為物件根本無法完成初始化。
super())StackOverflowError 屬於 Error,不可捕獲恢復,只能修正設計