java中"Static塊"是怎么回事,怎么用的,有什么意義  

6.Static塊  

Static塊:該類(lèi)的任何方法被首次觸碰到時(shí)(馬克-to-win: when you touch Test的main方法時(shí)),Static塊被運(yùn)行。可以在里面初始化你的static變量,不能訪問(wèn)實(shí)例變量。在所有靜態(tài)變量初始化之后運(yùn)行,見(jiàn)例子。
馬克- to-win:馬克 java社區(qū):防盜版實(shí)名手機(jī)尾號(hào): 73203。
本章源碼



class Test1{
    static {
        System.out.println("Static block Test1 initialized.");
    }
}
public class Test {
    /*下面兩句話(huà)是在靜態(tài)塊兒之前執(zhí)行,所以它的值,被靜態(tài)塊兒里面賦的值所覆蓋掉。馬克-to-win, the following two statements are before the execution of the static block.*/
    static int a = 3;
    static int b;
    int c;

    static void cal(int x) {
        System.out.println("x = " + x);
        System.out.println("a = " + a);
        System.out.println("b = " + b);
    }

    // 靜態(tài)塊兒Static block
    static {
        // c=9; 是錯(cuò)誤的,will cause an error.
        System.out.println("Static block initialized.");
        a = 9;
        b = a * 4;
        System.out.println("a = " + a);
        System.out.println("b = " + b);    }

    public static void main(String args[]) {
        System.out.println("in main");
/* main and cal 都是靜態(tài)塊兒,所以可以這樣調(diào)用,here main and cal is on the same class and same level, so can use in this way.*/
        cal(42);
        new Test1();
    }
}

結(jié)果:
Static block initialized.
a = 9
b = 36
in main
x = 42
a = 9
b = 36
Static block Test1 initialized.


Assignment: 3) bawei, static block {registration, pay tuition,} normal program is "start studying."