在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 兄妹拍照祝福语简短的话