Java一个demo看懂代码代码执行顺序

序言

很多人用java,但是又有多少人真的懂java,我就是对java不是很懂的那部分,还记得有次笔试题让我写代码执行顺序,当时一脸蒙,平时谁有去关心代码执行顺序的啊,只会觉得感觉是这样,写出的代码也没问题就对了。这个就大错特错了,下面还是用demo看下执行顺序吧!

上代码:

public class Insect {
    private int i=9;
    protected int j;
    Insect(){
        System.out.println("i="+i+",j="+j);
        j=39;
    }

    static {
        Insect.printInt("Insect static code");
    }

    private static int x1 = printInt("static Insect.x1 initialized");
    static int printInt(String s){
        System.out.println(s);
        return 47;
    }
}

public class Beetle extends Insect {
    private int k = printInt("Beetle.k initialized");

    public Beetle(){
        System.out.println("k="+k);
        System.out.println("j="+j);
    }

    private static int x2 = printInt("static Beetle.x2 initialized");

    public static void main(String[] args) {
        System.out.println("Beetle constructor");
        Beetle b = new Beetle();
    }
    static {
        Insect.printInt("Beetle static code");
    }
}

执行结果:
在这里插入图片描述

结论:
1.先静态再非静态
2.先父类再之类
3.先属性再构造
4.同级代码块自上而下

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值