Re: [問題] 匿名內部類別的建構函數怎麼用?

看板java作者 (sbr)時間16年前 (2009/05/03 18:33), 編輯推噓3(301)
留言4則, 3人參與, 最新討論串3/3 (看更多)
推 ozone:剛試了一下 initializer似乎是跑在constructor前面的?! 05/04 02:18 instance initializer 與 field initializer 都是由編譯器 insert/inline 到每一 個 constructor 裡最前面(after super constructor invocation)。 class Bar { public Bar(int n){} } class Foo extends Bar { String name = "A"; { name = "B"; } public Foo() { super(0); name = ""; } public Foo(String s) { super(0); name = s; } } 編譯出來的 class bytecode 會等同於(以 sun's Java Compiler 來說): class Foo extends Bar { String name; public Foo() { super(0); name = "A"; name = "B"; name = ""; } public Foo(String s) { super(0); name = "A"; name = "B"; name = s; } } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 218.173.138.198

05/04 11:10, , 1F
嗯, 變數的給值跟block的執行的確是在constructor之前.
05/04 11:10, 1F

05/04 11:58, , 2F
但是第一行是 this(...) 的 constructor 就不會加喔,
05/04 11:58, 2F

05/04 12:00, , 3F
不然會重複 initialize
05/04 12:00, 3F

05/04 14:19, , 4F
感謝 macbuntu 的補充說明
05/04 14:19, 4F
文章代碼(AID): #19_UENU8 (java)
文章代碼(AID): #19_UENU8 (java)