java的继承关系中对象的加载和初始化顺序

来源:互联网 发布:怎样参加淘宝活动 编辑:程序博客网 时间:2024/06/05 00:58
class Base {    public static Base t1 = new Base("父类--t1");    public static int k = 5;    public static Base t2 = new Base("父类--t2");    public static String s = "abcd";    public static int i = print("i");    public static int n = 99;    public int j = print("j");    {        print("父类--非静态构造块");    }    static {        print("父类--静态块");    }    public Base() {        System.out.println("子类调用父类构造方法");    }    public Base(String str) {        System.out.println((++k) + ":" + str + "   i=" + i + "    n=" + n + "   str=" + s + "  t1=" + t1 + "   t2=" + t2);        ++i;        ++n;    }    private static int print(String str) {        System.out.println((++k) + ":" + str + "   i=" + i + "   n=" + n + "   str=" + s + "  t1=" + t1 + "   t2=" + t2);        ++n;        return ++i;    }    /*    public static void main(String[] args) {        //Base t = new Base("父类---init");        //Base t2 = new Base("父类---init2");        System.out.println("\n\n========================\n\n");        Child c = new Child("子类---init");        Child c2 = new Child("子类---init2");    }*/}/** *   *  1 程序从main函数开始执行 ,执行main函数,需要先加载class文件 *  2 加载class文件的同时,同时初始化static成员变量和static块,执行顺序为从上到下依次执行 *  3 加载class完成之后,初始化成员变量。注:普通代码块,可以看作成员变量,执行顺序为从上到下依次执行 *  4 上面的过程完成之后,再从main函数的第一条语句开始执行。 *  5 注:静态成员变量和静态代码块只会 在加载class文件的时候 执行一次 */public class Child extends Base{    public static Child c1 = new Child("子类--c1");    public static int k1 = 10;    public static Child c2 = new Child("子类--c2");    public static String s1 = "abcd1";    public static int i1 = print("i1");    public static int n1 = 99;    public int j1 = print("j1");    {        print("子类--非静态构造块");    }    static {        print("子类--静态块");    }    public Child(String str) {        System.out.println((++k1) + ":" + str + "   i1=" + i1 + "    n1=" + n1 + "   str1=" + s1 + "  c1=" + c1 + "   c2=" + c2);        ++i1;        ++n1;    }    private static int print(String str) {        System.out.println((++k1) + ":" + str + "   i1=" + i1 + "   n1=" + n1 + "   str1=" + s1 + "  c1=" + c1 + "   c2=" + c2);        ++n1;        return ++i1;    }    public static void main(String[] args) {        //Base t = new Base("父类---init");        //Base t2 = new Base("父类---init2");        System.out.println("\n\n========================\n\n");        Child c = new Child("子类---init");        Child c2 = new Child("子类---init2");    }}/* * main方法要执行,需要先加载main方法所在的类的Class文件,有父类则需先加载父类 * 静态成员变量和静态代码块的初始化和加载Class文件是同步进行的,  *    所以加载Class文件的同时,完成静态代码块和静态成员变量的初始化工作  * Class文件加载完成之后,开始逐条语句执行 main方法  * 在new 对象实例的时候,也会先执行当前类的父类的构造器  * 类的实例化,会按顺序初始化 成员变量,最后执行构造函数  */

这里写图片描述

0 0