实现在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!