工作两年以上的coder基本上都会常常用到static关键字修饰符,比如常用的工具类中我们会经常声明一些常用的static静态方法,如在JDK中的java.lang.Math类和java.lang.System类中的所有方法都被声明成为static方法;另外在程序中的全局常量经常也被声明成为static静态成员变量,比如一些固定的公式中的指定值,如自然对数的底数e为java.lang.Math.E,还有圆周长与直径之比pi为java.lang.Math.PI等。
public class StaticTest {
private String str = "hello world";
// 静态成员变量
private static String str2 = "hello";
// 静态块
static {
new StaticClass("test");
}
//静态块
static {
System.out.println(str2);
}
// 静态类
static class StaticClass {
public StaticClass(String str) {
System.out.println(str);
}
}
private static String toSay(String str){
return str;
}
public static void main(String[] args) {
System.out.println(StaticTest.toSay("word"));
StaticTest test = new StaticTest();
System.out.println(test.str);
}
}
?执行结果:
test
hello
word
hello world
可见在运行main主方法后,在调用System.out.println(StaticTest.toSay("word"));时就已经打印了test和hello,说明在类被加载到内存就已经执行了静态块的内容,根据test和hello打印先后顺序可以判断静态块是按照在代码中的先后顺序而执行的,如果静态块中涉及到静态类,则执行静态类的构造方法,然后才是执行main方法里的代码。