写个例子求证网传的这三者的关系
1、每调用一次构造方法,则执行一次构造块
2、静态块只在类加载的时候加载一次
3、有多个静态块或构造块时,按声明顺序加载
4、加这点, static块优先于构造块,构造函数,是最先被执行的!
5、这三个模块函数的执行都优先于主函数(例子中的test()就是主函数)。
public class StaticBlock {
public void test(){
System.out.println("Running normal function!");
}
{
System.out.println("Running constructor block!");
}
public StaticBlock(){
System.out.println("Running constructor function!");
}
static {
System.out.println("Running static block!");
}
public static void main(String[] args) {
StaticBlock staticBlock = new StaticBlock();
staticBlock.test();
StaticBlock staticBlock1 = new StaticBlock();
staticBlock1.test();
}
}
执行结果:
Running static block! //静态块只在类加载的时候加载一次
Running constructor block! //每调用一次构造方法,则执行一次构造块
Running constructor function!
Running normal function!
Running constructor block!
Running constructor function! //每调用一次构造方法,则执行一次构造块
Running normal function!
增加一个构造块,和一个静态块:
public class StaticBlock {
public void test(){
System.out.println("Running normal function!");
}
{
System.out.println("Running constructor block2!");
}
{
System.out.println("Running constructor block1!");
}
public StaticBlock(){
System.out.println("Running constructor function!");
}
static {
System.out.println("Running static block2!");
}
static {
System.out.println("Running static block1!");
}
public static void main(String[] args) {
StaticBlock staticBlock = new StaticBlock();
staticBlock.test();
StaticBlock staticBlock1 = new StaticBlock();
staticBlock1.test();
}
}
结果:
Running static block2! //有多个静态块或构造块时,按声明顺序加载
Running static block1!
Running constructor block2! //有多个静态块或构造块时,按声明顺序加载
Running constructor block1!
Running constructor function!
Running normal function!
Running constructor block2!
Running constructor block1!
Running constructor function!
Running normal function!