java构造函数 静态块_[Java] 静态块,构造块,构造函数,普通函数的执行顺序

写个例子求证网传的这三者的关系

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!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值