Static block是Java中的一個用來初始化Static屬性的功能
一個Class中的Static block只會執行一次
建構子(constructor)則是每次new一個物件的時候就會執行一次

建構子的名稱要與class名稱相同,並且不允許同樣參數的建構子

使用static block與constructor的方法範例如下

public class StaticInitDemo {

private static String message;

private String message2;



static{

System.out.println("static block initialize");

setMessage("This is an demo of static block");

}



public StaticInitDemo(){

System.out.println("constructor initialize");

setMessage2("This message is generate as constructor");

}

public StaticInitDemo(String str){

System.out.println("constructor with parameter initialize");

setMessage2("str="+str);

}

public static String getMessage() {

return message;

}

public static void setMessage(String message) {

StaticInitDemo.message = message;

}

public String getMessage2() {

return message2;

}

public void setMessage2(String message2) {

this.message2 = message2;

}



}//end of class



public class StaticBlockDemo {



public static void main(String[] args) {

System.out.println("Test begin\n");



System.out.println("StaticBlock:");

System.out.println(StaticInitDemo.getMessage());



System.out.println("\n"+"Constructor:");

StaticInitDemo demo = new StaticInitDemo();

System.out.println(demo.getMessage2());

StaticInitDemo demo2 = new StaticInitDemo();



}



}//end of class


執行結果為:
Test begin

StaticBlock:
static block initialize
This is an demo of static block

Constructor:
constructor initialize
This message is generate as constructor
constructor initialize


arrow
arrow
    全站熱搜
    創作者介紹
    創作者 Dnight 的頭像
    Dnight

    D奈老師的部落格

    Dnight 發表在 痞客邦 留言(0) 人氣()