Re: [問題] 在建構子殺掉自己的問題

看板java作者 (godfat 真常)時間19年前 (2007/03/20 21:42), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串5/5 (看更多)
※ 引述《montreal (╮(╯3╰)╭)》之銘言: : public class Tester { : AnotherClass aClass = null; : public Tester() { : aClass = new AnotherClass(this); ^^^^^^^^^^^^^^^^^^^^^^ 這裡把 aClass 設為 null, 然後呢? new 會傳回東西是吧? 所以 aClass != null : if(aClass == null) : System.out.println("aClass == null"); : else : System.out.println("aClass != null"); : } : public void killAnotherClass() { : aClass = null; : } : class AnotherClass { : AnotherClass(Tester parent) { : parent.killAnotherClass(); ^^^^^^ 其實 nested class 本身就有 pointer/reference 指向 enclosing class 所以這邊不用吃 parent, 直接 killAnotherClass(); 即可 多傳 parent 就變傳兩次了(其中一次是 compiler 幫你做掉的) : } : } : public void killAnotherClass() { : aClass = new AnotherClass(this, "name b"); ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ c'tor 還沒結束又再次喚起,你知道了 基本上 stack 會 overflow 大概有 99% 是無窮遞迴 : } : class AnotherClass { : String name; : AnotherClass(Tester parent, String _name) { : name = _name; : parent.killAnotherClass(); : } : } -- Hear me exalted spirits. Hear me, be you gods or devils, ye who hold dominion here: I am a wizard without a home. I am a wonderer seeking refuge. Sacrifice -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 220.134.30.220
文章代碼(AID): #15_-JYGA (java)
討論串 (同標題文章)
文章代碼(AID): #15_-JYGA (java)