2015-09-27 20 views
0

我試圖找到關於此特異性的答案,但找不到任何答案。只有Static關鍵字作爲標題的括號內的指令

我在下面的代碼中有一個括號內只有static關鍵字作爲標題的指令。

我的確清楚它的功能,並可以像其他static方法/變量一樣猜測它們的用途,但我無法給它起個名字。

它不是一個變量也不是一個方法(它不會返回任何東西,甚至不包括「void」),並且肯定不是構造函數,因爲使用了static關鍵字。

我們稱這種特殊的「方法」是什麼?

下面是代碼:

public class Test{ 

    static { 
     System.out.println("What do we call this?"); 
    } 

    public Test(){ 
     System.out.println("Instance of Test created"); 
    } 

    public static void main(String[] args) { 
     new TestSon().go(); 
    } 

    public void go(){ 
     System.out.println("Go method Test"); 
    } 

} 

class TestSon extends Test{ 

    static { 
     System.out.println("Same here..."); 
    } 

    public TestSon(){ 
     System.out.println("Instance of TestSon created"); 
    } 

    @Override 
    public void go() { 
     System.out.println("Go method son"); 
    } 
} 

輸出:

What do we call this? 
Same here... 
Instance of Test created 
Instance of TestSon created 
Go method son 

回答

1

閱讀更多關於它是稱爲初始化塊,它可以是靜態的(每個類一次),也可以不是每個對象實例的初始化。

一個典型的使用:

public A { 

    static final Map<String, String> TRANSLATIONS = new HashMap<>(); 
    static { 
     TRANSLATUIBS.put("un", "one"); 
     TRANSLATUIBS.put("deux", "two"); 
     TRANSLATUIBS.put("trois", "three"); 
    } 

    final URL MY_HOME_PAGE; 
    { 
     try { 
      MY_HOME_PAGE = new URL("..."); 
     } catch (MalformedURLException e) { 
      throw new IllegalStateException(); 
     ] 
    } 

對於非靜態初始化,代碼已被放置在一個構造函數。

靜態初始化器在類的第一次使用時被調用。所以如果不使用這個類,它不一定會被調用。

+0

謝謝,現在更清晰:) –