java中"Static塊"是怎麼回事,怎麼用的,有什麼意義 ...
Static塊:該類的任何方法被首次觸碰到時(馬克-to-win: when you touch Test的main方法時),Static塊被運行。可以在裡面初始化你的static變數,不能訪問實例變數。在所有靜態變數初始化之後運行,見例子。
class Test1{
static {
System.out.println("Static block Test1 initialized.");
}
}
public class Test {
/*下麵兩句話是在靜態塊兒之前執行,所以它的值,被靜態塊兒裡面賦的值所覆蓋掉。馬克-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);
}
// 靜態塊兒Static block
static {
// c=9; 是錯誤的,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");
。。。。。。。。。。。。。。。。。。。
詳情請見:http://www.mark-to-win.com/index.html?content=JavaBeginner/javaUrl.html&chapter=JavaBeginner/JavaBeginner2_web.html#StaticBlock