甲静块是代码使用静态关键字的块。通常,这些用于初始化静态成员。JVM在类加载时在main方法之前执行静态块。
public class MyClass {
static{
System.out.println("Hello this is a static block");
}
public static void main(String args[]){
System.out.println("This is main method");
}
}Hello this is a static block This is main method
JVM首先寻找main方法(至少是最新版本),然后开始执行包含静态块的程序。因此,如果没有main方法,就无法执行静态块。
public class Sample {
static {
System.out.println("Hello how are you");
}
}由于上述程序没有main方法,因此如果编译并执行它,将会收到错误消息。
C:\Sample>javac StaticBlockExample.java C:\Sample>java StaticBlockExample Error: Main method not found in class StaticBlockExample, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application
如果要执行静态块,则需要具有Main方法,并且该类的静态块必须在main方法之前执行。
public class StaticBlockExample {
static {
System.out.println("This is static block");
}
public static void main(String args[]){
System.out.println("This is main method");
}
}This is static block This is main method