实际使用中的例子,挺方便的哦 /** * Checks if java version is >= 1.4, sets application title and icon, as * well as logo icon. */ static { try { String vers = System.getProperty("java.version"); if (vers.compareTo("1.4") < 0) { System.out.println("!!!WARNING: JaWE must be run with a " + "1.4 or higher version VM!!!"); System.exit(1); } } catch (Throwable t) { System.err.println("uncaught exception: " + t); t.printStackTrace(); } }
StringBuffer buf1 = new StringBuffer(100);
for (int i = 0; i < 3; i++) {
buf1.append(i);
}
...
}
这是一个静态块,在类中只有成员和方法,你除了在方法中使用FOR之类的语句,在方法外是不行的!!!而用STATIC就可以不用方法,起到申明变量的好处!!以前上课是这样听的,太久了,忘记了!!!呵呵
StringBuffer中间没有空格
当第一次执行到该static区块的时候,判断为false,然后就执行之,然后再把这个布尔变量取反,下一次流程进行到该static区块的时候就不会再执行了。
class MyObject{
int a;
int b=4;
AnotherObject ao1;
AnotherObject ao2;
static{
ao1 = new AnotherObject();
ao2 = new AnotherObject();
//a = 5;没必要
}
MyObject(){
a = 5;
}
}
时首先初始化成员(object对象放在static块中)a=0,b=4,再执行构造方法a=5,后生成了一个MyObjet对象。然而此对象可能由于某些随机因素并不会在每次程序执行过程中使用,且AnotherObject是一个比较“大”的对象,那就使用此法来做吧。我是这样理解的。
/**
* Checks if java version is >= 1.4, sets application title and icon, as
* well as logo icon.
*/
static
{
try
{
String vers = System.getProperty("java.version");
if (vers.compareTo("1.4") < 0)
{
System.out.println("!!!WARNING: JaWE must be run with a " +
"1.4 or higher version VM!!!");
System.exit(1);
}
}
catch (Throwable t)
{
System.err.println("uncaught exception: " + t);
t.printStackTrace();
}
}
初始化结束后,如果要修改的话,该怎么做啊?