java基础学习笔记——静态初始化块,初始化块,构造函数的执行顺序

博客主要探讨了Java中static file和static代码块、filed和代码块的执行顺序,指出谁在前谁先执行,而构造函数最后执行,还提及参考内容为Java初始化块、静态初始化块及构造函数执行顺序及用途探究。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码:

// 数字即表示执行顺序
class A {
    String filed = func("5: filed of A");

    static String staticFiled = func("1: static filed of A");

    {
        func("6: code block of A");
    }

    static {
        func("2: static code block of A");
    }


    A() {
        func("7: constructor of A");
    }

    static String func(String message) {
        System.out.println(message);
        return message;
    }
}

class B extends A {

    {
        func("8: code block of B");
    }

    static {
        func("3: static code block of B");// 接着是子类static file和static代码块
    }

    B() {
        func("10: constructor of B");
    }

    String filed = func("9: filed of B");

    static String staticFiled = func("4: static filed of B");
}


public class Test1 {
    public static void main(String[] args) {
        B b = new B();
    }
}

输出:

1: static filed of A
2: static code block of A
3: static code block of B
4: static filed of B
5: filed of A
6: code block of A
7: constructor of A
8: code block of B
9: filed of B
10: constructor of B

总结

  1. static file和static代码块谁在前谁先执行
  2. filed和代码块谁在前谁先执行
  3. 构造函数最后执行

参考:

Java的初始化块、静态初始化块、构造函数的执行顺序及用途探究

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值