• Java类(继承)初始化顺序


    /**
     * Created by xfyou on 2016/11/2.
     * Java继承的初始化
     */
    public class Beetle extends Insect {
        int k = prt("Beetle.k initialized");
    
        public Beetle() {
            prt("k = " + k);
            prt("j = " + j);
        }
    
        static int x2 = prt("static Beetle.x2 initialized");
    
        static int prt(String s) {
            System.out.println(s);
            return 63;
        }
    
        public static void main(String[] args) {
            prt("Beetle constructor");
            Beetle b = new Beetle();
        }
    }
    
    class Insect {
        int i = 9;
        int j;
    
        public Insect() {
            prt("i = " + i + ", j = " + j);
            j = 39;
        }
    
        static int x1 = prt("static Insect.x1 initialized");
    
        static int prt(String s) {
            System.out.println(s);
            return 47;
        }
    }

    执行结果如下:

    static Insect.x1 initialized

    static Beetle.x2 initialized

    Beetle constructor

    i = 9, j = 0

    Beetle.k initialized

    k = 63

    j = 39

    执行顺序总结:

    1、父类静态字段

    2、父类静态初始化块

    3、子类静态字段

    4、子类静态初始化块

    5、父类实例字段

    6、父类实例初始化块

    7、父类构造器

    8、子类实例字段

    9、子类实例初始化块

    10、子类构造器

     

    没有继承的单个类的初始化顺序为:

    • 静态字段
    • 静态初始化块
    • 实例字段
    • 实例初始化块
    • 构造器

     

  • 相关阅读:
    Elasticsearch 检索
    Elasticsearch 基本操作
    Elasticsearch 集群
    Elasticsearch 插件head和kibana
    Elasticsearch 安装
    CentOS 安装JDK
    前端登录密码加密传输
    springboot2.0 快速集成kafka
    原来自定义模型绑定器还可以这么玩
    Value cannot be null or empty. 参数名: contentPath
  • 原文地址:https://www.cnblogs.com/frankyou/p/6023662.html
Copyright © 2020-2023  润新知