Re: [問題] Class中的大括號
※ 引述《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
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
06/26 11:53, 5F
推
06/26 12:13, , 6F
06/26 12:13, 6F
→
06/26 23:59, , 7F
06/26 23:59, 7F
→
06/28 17:34, , 8F
06/28 17:34, 8F
討論串 (同標題文章)
java 近期熱門文章
PTT數位生活區 即時熱門文章