java代码执行加载顺序

java代码执行加载顺序

1.在JAVA中用{}括起来的代码称为代码块,根据定义位置和申声明关键字不同,分为4类:

普通代码块,构造块,静态块,同步代码块

2.加载顺序:

public class Parent {

    static PrintMsg pm = new PrintMsg("parent-static-filed");
    public PrintMsg pm2 = new PrintMsg("parent-common-filed");

    static {
        System.out.println("parent-static-block");
    }

    {
        System.out.println("parent-common-block");
    }
    public Parent(){
        System.out.println("parent-no-arg-method");
    }
    public static void send(){
        System.out.println("parent-static-method-send");
    }

}
public class Child extends Parent{

    static PrintMsg pm = new PrintMsg("child-static-filed");
    public PrintMsg pm2 = new PrintMsg("child-common-filed");

    static {
        System.out.println("child-static-block");
    }

    {
        System.out.println("child-common-block");
    }
    public Child(){
        System.out.println("child-no-arg-method");
    }
    public static void send(){
        System.out.println("child-static-method-send");
    }


}
public class MainTest {
    public static void main(String[] args) {
        Child child = new Child();
        child.send();
    }
}

image-20210124172839163

执行可知:

1.静态变量 >> 静态代码块 >> 实例变量 >> 实例代码块 >> 实例构造器 >> 实例方法(这个是主动调用的)

2.静态层级:静态变量和方法先执行,若有继承关系,则父类先执行静态逻辑,而后子类再执行静态逻辑。

3.实例层级:当父子静态逻辑一并执行完后,才开始执行实例层级,同静态逻辑一样,先执行父类再执行子类

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值