VM首先寻找主要方法(至少是最新版本),然后开始执行包含静态块的程序。因此,如果没有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
最后
以上就是平常毛豆最近收集整理的关于java中必须有main方法才能执行吗_在Java中如何在没有main方法的情况下执行静态块?...的全部内容,更多相关java中必须有main方法才能执行吗_在Java中如何在没有main方法内容请搜索靠谱客的其他文章。
发表评论 取消回复