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

来源:互联网 发布:视频裁剪大小软件 编辑:程序博客网 时间:2024/04/29 21:09
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时发现它是子类,而子类是父类派生的,因此要想加载子类必须先加载父类!
加载父类时,首先将父类的类信息、静态变量、静态代码块加载到方法去,因此首先父类的静态代码块被执行;
加载完父类,然后加载子类,同样子类的静态代码块被得到执行;
当类加载完,需要创建对象,在创建对象前首先执行非静态代码块,因为子类隐式调用父类构造方法,因此首先执行父类的非静态块,紧接着再执行父类的构造方法;
然后程序创建子类对象,发现子类中也包含非静态块,于是先执行非静态块,紧接着执行构造方法中其他代码!
非静态块在对象创建时执行,并且每次创建都会执行,由此可以看到,非静态块就相当于类的成员变量,在创建对象调用构造方法前执行。一旦对象创建完成,此后该对象的非静态块就再也不会执行!

原创粉丝点击