Java 构造函数执行顺序

归纳自《JAVA编程思想》

概述

Java中构造函数调用按以下顺序进行:

  1. 找寻所有的基类(父类)

  2. 按基类→导出来的顺序初始化静态成员(静态成员只会初始化一次,对应类)

  3. 按基类→导出类的顺序构造对象(构造对象将会执行4,5两个步骤)

  4. 初始化非静态成员(非静态成员在每次构造对象的时候都会初始化一次,对应所构造的对象)

  5. 调用相应的构造函数

    示例代码

    class FatherA{

    public FatherA(){
        System.out.println("FatherA");
    }

    }

    class FatherB{

    public FatherB(){
        System.out.println("FatherB");
    }

    }

    class FatherAther{

    public FatherAther(){
        System.out.println("Father Constructor");
    }
    
    private static FatherA FatherA = new FatherA();
    private FatherB FatherB = new FatherB();

    }

    class SonA{

    public SonA(){
        System.out.println("SonA");
    }

    }

    class SonB{

    public SonB(){
        System.out.println("SonB");
    }

    }

    class Son extends FatherAther{

    public Son(){
        System.out.println("Son Constructor");
    }
    
    private static SonA SonA = new SonA();
    private SonB SonB = new SonB();

    }

    public class JavaConstructor{

    public static void main(String[] args){
        new Son();
        System.out.println("-----------");
        new Son();
    }

    }

运行结果

运行结果