用code观察java类的初始化顺序

原创文章转载请注明出处:https://blog.csdn.net/kings963/article/details/105449346

 

类的加载顺序是java中比较重要的基础知识~!

或许你知道static肯定是优先加载的,因为它是属于类class的但是和类的实例无关的这么一个概念,

还有代码块 block和静态代码块等知识点~!

其实我觉得都 不如 自己手打一些例子 来加深印象更好 ~

以下是我简单整理的一个例子~

/**
 * 看懂java初始化顺序
 */
class Insect {

    public static int CountNum = 1;

    private int superI = 9;
    protected int superJ;

    public static int superK = -1;


    {
        int j = 11;
        System.out.println(CountNum++ + " super block-----superI = " + j + "| j = " + j);
    }

    static {
        superK = 6;
        System.out.println(CountNum++ + " static super block----- = " + "| j = " + superK);
    }

    Insect() {
        System.out.println(CountNum++ + " super construc superI----- = " + superI + "| superJ = " + superJ);
        superJ = 39;
    }


    /**
     * @param s
     * @return
     */
    static int printInit(String s) {
        System.out.println(s);
        return 47;
    }
    private static int x1 = printInit(CountNum++ + " static super-----Insect.x1 initialized");
}


public class JichengTest001 extends Insect {
    private int childI = 9;
    protected int childJ;

    public static int childK = -1;

    {
        int j = 11;
        System.out.println(CountNum++ + " child block-----childI = " + childI + "| j = " + j);
    }

    static {
        childK = 6;
        System.out.println(CountNum++ + " static child block----- = " + "| childK = " + childK);
    }

    private int k = printInit(CountNum++ + " child JichengTest001.k initialized-----");

    public JichengTest001() {
        System.out.println(CountNum++ + " child construct---k = " + k);
        System.out.println(CountNum++ + " child construct---j = " + childJ);
    }

    private static int x2 = printInit(CountNum++ + " static child JichengTest001.x2 initialized-----");

    public static void main(String[] args) {
        System.out.println(CountNum++ + " child JichengTest001 main()");
        JichengTest001 b = new JichengTest001();
    }

}

加载进你的IDE打印下你会发现如下结果:

1 static super block----- = | j = 6
2 static super-----Insect.x1 initialized
3 static child block----- = | childK = 6
4 static child JichengTest001.x2 initialized-----
5 child JichengTest001 main()
6 super block-----superI = 11| j = 11
7 super construc superI----- = 9| superJ = 0
8 child block-----childI = 9| j = 11
9 child JichengTest001.k initialized-----
10 child construct---k = 47
11 child construct---j = 0

结论:

1.静态块和静态变量优先级一样,代码由上自下加载:

2.静态 优先

3.有父类优先加载父类

剩下的大家自己观察吧~

祝 好运

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值