2014-04-29 70 views
2

很生鏽,但我很確定我從來沒有見過這樣寫的代碼。這是一個模擬問題從Java夥伴考試可能有人告訴我是否'靜態'在第10行連接到go()方法?主要是爲什麼輸出是x y c g ???靜態在這裏指的是什麼

public class testclass { 

    testclass() { 
     System.out.print("c "); 
    } 

    { 
     System.out.print("y "); 
    } 

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

    void go() { 
     System.out.print("g "); 
    } 

    static { 
     System.out.print("x "); 
    } 

} 
+1

可能重複:http://stackoverflow.com/questions/2943556/static-block-in-java – user432

+0

'靜態{}'被添加到的靜態初始化類。當這個類被初始化時,它從上到下執行。 –

+0

ahh ..這就解釋了爲什麼要首先打印x.謝謝ya'll – Leonne

回答

0
static { System.out.print("x "); } 

這是靜態初始化塊。這將在課程加載時被調用。因此先打電話。

{ System.out.print("y "); } 

這是非靜態初始化塊。一旦創建對象,就會被稱爲第一件事。

testclass() { System.out.print("c "); } 

這是構造函數。在執行所有初始化塊後,將在對象創建過程中執行。

最後,

void go() { System.out.print("g "); } 

普通方法調用。最後要執行的事情。

有關詳細信息,請參閱http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html

1

這是縮進的代碼。在上面的類,你有

  1. 構造
  2. 一類塊
  3. 靜態塊
  4. 和被叫方法go()

class testclass { 

/** 
* Constructor, which gets called for every new instance, after instance block 
*/ 
testclass() { 
     System.out.print("c "); 
} 

/** 
* This is instance block which gets called for every new instance of the class 
* 
*/ 
{ 
    System.out.print("y "); 
} 

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

/** 
* any method 
*/ 
void go() { 
     System.out.print("g "); 
} 

/** 
* This is static block which is executed when the class gets loaded 
* for the first time 
*/ 
static { 
     System.out.print("x "); 
} 

} 
3

告訴我是否l中的'靜態' ine 10連接到go() 方法??

這與go方法無關。它被稱爲靜態初始化塊。

爲什麼輸出是x y c g ???

以下是執行在Java

  1. 在類加載時間的順序,靜態字段/初始化塊將被執行。
  2. 在創建對象的時候,JVM領域設置爲默認初始值(0,假,空)
  3. 調用構造函數對象(但不執行的身體構造的又)
  4. 調用使用初始值設定和初始化塊超
  5. 初始化字段的構造
  6. 執行構造的主體
+0

這個問題的絕對副本(http ://stackoverflow.com/questions/13699075/calling-a-java-method-with-no-name),並應標記爲重複 –

0

靜態塊將首先intialised作爲類負載。多數民衆贊成你得到O/P的原因

x as the first output 
0

它是靜態初始化塊。所以當你創建該類的對象時,它甚至在構造函數之前首先運行靜態初始化塊。