静态代码块不包含在任何方法体中,当类被载入时自动执行静态代码块,且只被执行一次经,常用于类属性的初始化
静态方法 百度一下
StaticCode 方法如下
package org.dalong.staticblockcode;
/**
* @author HuangDaLong
*
* TODO To change the template for this generated type comment go to Window -
* Preferences - Java - Code Style - Code Templates
*/
public class StaticCode {
protected static String teststring;
static {
System.out.println("call staticcode successful!");
System.out.println("This is teststring: "+teststring );
}
protected static void staticMetho(){
System.out.println("hello,This is Static metho!");
teststring="Static metho made this string!";
}
public String getTeststring() {
return teststring;
}
public void setTeststring(String teststring) {
this.teststring = teststring;
}
}
测试方法如下,大家可以比较一下输出的结果;
package org.dalong.staticblockcode;
/**
* @author HuangDaLong
*
* TODO To change the template for this generated type comment go to Window -
* Preferences - Java - Code Style - Code Templates
*/
public class StaticCodeTest {
public static void main(String args[]) {
/**
* print:call staticcode successful!
* This is tststring:null
*/
new StaticCode();
/**
* no print;
*/
new StaticCode();
/**
* no print;
*/
StaticCode sc = new StaticCode();
/**
* print: null
*/
System.out.println(sc.getTeststring());
/**
* print: hello test;
*/
sc.setTeststring("hello,test!");
System.out.println(sc.getTeststring());
/**
* print:hello,This is Static metho!
*/
StaticCode.staticMetho();
/**
* print:Static metho made this string!
*/
System.out.println(sc.getTeststring());
}
}