实现在main()方法执行前输出“hello world!”
程序运行前最先加载的就是mian()方法,但并不意味着是程序运行时第一个被执行的模块
静态块在类加载时就会被调用,因此可以在main()方法执行前,利用静态块来实现输出“hello world!”功能,如下代码:
public class Test{
static{
System.out.println("hello world!");
}
public static void main(String[] args){
System.out.println("this is main method!");
}
}
程序运行结果:
hello world!
this is main method!
本文介绍如何在Java程序的main方法执行之前输出“HelloWorld!”通过使用静态初始化块来实现这一目标。
1万+

被折叠的 条评论
为什么被折叠?



