java static块和非static块的执行顺序

本文详细解析了Java中父类和子类的构造方法及非静态代码块的执行顺序,阐述了类加载过程以及对象创建时的具体执行流程。

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

package test;

public class Parent {

    public Parent(){
        System.out.println("constructor in parent");
    }

    {
        System.out.println("not static in parent");
    }

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

}
public class Child extends Parent {

    public Child(){
        System.out.println("contstructor in child");
    }

    {
        System.out.println("not static in child");
    }

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

    public static void main(String[] args){
        new Child();
        Utils.testUtils();
        Utils u1=new Utils();
        Utils u2=new Utils();
        u1.count();
        u2.count();
        /*
         * static in parent  //在类加载前首先加载类信息和静态块
         * static in child
         * not satic in parent//在创建对象时,调用构造方法前执行非静态快
         * constructor in parent
         * not static in child
         * constructor in child
         * static in utils
         * testUtils //Utils对象没有创建,非static块没有被加载,因此非static块只有在创建对象的时候才会执行
         * not static in utils//每创建一次对象,非static块执行一次
         * not static in utils
         * object.count()//此后在调用方法时,非静态块不会再被执行
         * object.count()
         */
    }
}

在new Child 时,首先会加载Child类,而加载Child时发现它是子类,而子类是父类派生的,因此要想加载子类必须先加载父类!
加载父类时,首先将父类的类信息、静态变量、静态代码块加载到方法去,因此首先父类的静态代码块被执行;
加载完父类,然后加载子类,同样子类的静态代码块被得到执行;
当类加载完,需要创建对象,在创建对象前首先执行非静态代码块,因为子类隐式调用父类构造方法,因此首先执行父类的非静态块,紧接着再执行父类的构造方法;
然后程序创建子类对象,发现子类中也包含非静态块,于是先执行非静态块,紧接着执行构造方法中其他代码!
非静态块在对象创建时执行,并且每次创建都会执行,由此可以看到,非静态块就相当于类的成员变量,在创建对象调用构造方法前执行。一旦对象创建完成,此后该对象的非静态块就再也不会执行!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值