在Java中何时何地执行静态块?
甲静块是代码使用静态关键字的块。通常,这些用于初始化静态成员。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
热门推荐
10 朋友新年祝福语大全 简短
11 新年祝福语简短大方兔年
12 搬新家礼物祝福语简短
13 同学见面花束祝福语简短
14 五一假期祝福语幽默简短
15 离职欢送敬酒祝福语简短
16 对学弟的祝福语简短
17 考老师辞职祝福语简短
18 祝福语驱散霉运的话简短