Java中关于静态块,初始化快,构造函数的执行顺序

代码如下:

public class ParentDemo {

    static {
        System.out.println("this is ParentDemo static");
    }

    {
        System.out.println("this is ParentDemo code block");
    }
    public ParentDemo() {
        System.out.println("this is ParentDemo constructor");
    }

}


public class SonDemo extends ParentDemo{


    static {
        System.out.println("this is SonDemo static");
    }

    {
        System.out.println("this is SonDemo code block");
    }
    public SonDemo() {
        System.out.println("this is SonDemo constructor");
    }
}

public class TestMain {

    public static void main(String[] args){
        new SonDemo();
    }

}

输出结果:
this is ParentDemo static
this is SonDemo static
this is ParentDemo code block
this is ParentDemo constructor
this is SonDemo code block
this is SonDemo constructor

由上可见,Java中 静态块中的代码在类加载时执行,子类继承父类。会按照继承的顺序先执行静态代码块。当实例化对象的时候,同理会按照继承的顺序依次执行如下代码:
代码块,构造函数,当父类的执行完以后,再执行子类。

总结:
第一次写博客,略显青涩。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值