Java:Initilization block

Code Example
class Layout {
 {
  System.out.println(getClass().getName() +
   " initialization block called.");
 }
 static {
  System.out.println(Layout.class.getName() +
   " static initialization block called.");
 }
 Layout() {
  System.out.println(getClass().getName() +
   " constructor called.");
 }
 void method() {
  System.out.println(getClass().getName() +
   " method called.");
 }
 public static void main(String [] arg) {
  System.out.println("main method celled.");
  System.out.println("start to build an Layout Object.");
  new Layout().method();
  System.out.println("build another Layout Object.");
  new Layout();
  System.out.println("main method complete.");

 }
}

Initilization block & static initilization block

執行之後的結果應該是
Layout static initialization block called.
main method celled.
start to build an Layout Object.
Layout initialization block called.
Layout constructor called.
Layout method called.
build another Layout Object.
Layout initialization block called.
Layout constructor called.
main method complete.
static initializtion black 在類別被JVM載入的時候會呼叫,而 initializtion black則是在物件建立的時,首先被呼叫的

留言