Re: [問題] Class中的大括號

看板java作者 (自立而後立人)時間11年前 (2014/06/26 02:28), 編輯推噓3(305)
留言8則, 7人參與, 最新討論串2/3 (看更多)
※ 引述《Lest ()》之銘言: : class A { : { : System.out.println("123"); : } : public A(){ : System.out.println("345"); : } : } : 請問一下JAVA高手,我學過的JAVA Class內只能包含建構子、方法及變數 : 那為何我的Class A又可以存在一個大括號。 : 當我new A(); 會顯示如下: : 123 : 345 : 為何大括號的123會執行呢???? 這個其實官網教學中有提到,概略翻譯一下應該就蠻能理解的。 http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html Normally, you would put code to initialize an instance variable in a constructor. There are two alternatives to using a constructor to initialize instance variables: initializer blocks and final methods. Initializer blocks for instance variables look just like static initializer blocks, but without the static keyword: { // whatever code is needed for initialization goes here } The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors. 一般來說你應該把初始化一個變數成員的行為放在 constructor, 但還是有其他兩個方法可以應用,其中一個就是你提到的這個初始化 block。 它會把這個 {} 裡面的程式碼放進每個建構子裡面, 這樣就可以用來在多個建構子裡面共用程式碼。 (但我個人是不會建議這麼做就是了。) -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 61.231.162.229 ※ 文章網址: http://www.ptt.cc/bbs/java/M.1403720926.A.E71.html

06/26 09:49, , 1F
推!! instance init比較少用..static init倒是比較常用
06/26 09:49, 1F

06/26 10:10, , 2F
感謝新板主講解,話說現在這個標題可以換掉嗎?
06/26 10:10, 2F

06/26 10:16, , 3F
有一種被放嘲諷的感覺
06/26 10:16, 3F

06/26 11:49, , 4F
疑? 版主換人了
06/26 11:49, 4F

06/26 11:53, , 5F
這當然,馬上來處理 XD
06/26 11:53, 5F

06/26 12:13, , 6F
咦?我還以為我來到 Ajax 版
06/26 12:13, 6F

06/26 23:59, , 7F
(筆記)
06/26 23:59, 7F

06/28 17:34, , 8F
一段時間沒來版主真的換人了OAOa
06/28 17:34, 8F
文章代碼(AID): #1JgnJUvn (java)
討論串 (同標題文章)
本文引述了以下文章的的內容:
以下文章回應了本文
完整討論串 (本文為第 2 之 3 篇):
文章代碼(AID): #1JgnJUvn (java)