Java代码块(静态和非静态)在子父类中的执行顺序

话不多说,直接上代码:

/**
 * @Author: YuShiwen
 * @Date: 2020/11/17 9:01 PM
 * @Version: 1.0
 */

class Root{
    static{
        System.out.println("Root static block");
    }
    {
        System.out.println("Root no static block");
    }
    public Root(){
        super();
        System.out.println("Root no parameter");
    }
}

class Mid extends Root{
    static{
        System.out.println("Mid static block");
    }
    {
        System.out.println("Mid no static block");
    }
    public Mid(){
        super();
        System.out.println("Mid no parameter");
    }

    public Mid(String msg){
        this();
        System.out.println("Mid constructor:"+msg);
    }
}

class Leaf extends Mid{
    static{
        System.out.println("Leaf static block");
    }
    {
        System.out.println("Leaf no static block");
    }
    public Leaf(){
        super("YuShiwen");
        System.out.println("Leaf no parameter");
    }
}

public class LeafTest {
    public static void main(String[] args) {
        new Leaf();
        System.out.println();
        new Leaf();
    }
}

输出结果:

Root static block
Mid static block
Leaf static block
Root no static block
Root no parameter
Mid no static block
Mid no parameter
Mid constructor:YuShiwen
Leaf no static block
Leaf no parameter

Root no static block
Root no parameter
Mid no static block
Mid no parameter
Mid constructor:YuShiwen
Leaf no static block
Leaf no parameter

Process finished with exit code 0

代码分析:
可以看出,静态代码块内的语句由父类到子类最先执行,且只执行一次,这是因为静态代码块虽类的加载而加载;
之后每创建一次对象的时候,由父及子,先执父类中的普通代码块,再执行父类中的构造器,然后在执行子类中的普通代码块,再执行子类中的构造器。

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MrYuShiwen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值