子类继承父类的时候构造器和非静态自由块的调用顺序

子类继承父类的时候构造器和非静态自由块的调用顺序
new 一个子类的时候的访问顺序:



class Creature {
    {
        System .out. println("creature 的非静态初始化 ");
    }

    public Creature () {
         super();
        System .out. println("creature 的构造方法 ");
    }

}

class Animal extends Creature {
    {
        System .out. println("animal 的非静态初始化 ");
    }

    public Animal () {
         super();
        System .out. println("animal 的构造方法 ");
    }

}

public class Monkey extends Animal {
    {
        System .out. println("monkey 的非静态初始化 ");
    }

    public Monkey () {
         super();
        System .out. println("monkey 的构造方法 ");
    }

    public static void main (String[] args) {
         new Monkey();
    }

}

输出结果:



非静态初始化块的执行总是先于构造器执行的



super(Para p1,Para p2......); 根据参数调用父类对应的构造方法

this(Para p1,Para p2......);  根据参数调用本类对应的构造方法

对于一个无参的构造器,会有一个默认的super(),她会调用父类的无参的构造方法





















原文地址:https://www.cnblogs.com/ZhangJinkun/p/4531702.html