zoukankan      html  css  js  c++  java
  • 一篇文章讲清楚父类子类的加载顺序

    使用两个类,一个父类,一个子类

    父类代码:

     1 public class Parent {
     2     public static int i = 10;
     3     private int j = 15;
     4 
     5     static {
     6         System.out.println("parent 静态代码块,无静态变量");
     7     }
     8 
     9     static {
    10         i = i + 100;
    11         System.out.println("parent 静态代码块,有静态变量,i=" + i);
    12     }
    13 
    14     {
    15         System.out.println("parent 代码块,无静态变量");
    16     }
    17 
    18     {
    19         j = j + 200;
    20         System.out.println("parent 代码块,有静态变量,j=" + j);
    21     }
    22 
    23     public Parent() {
    24         System.out.println("parent 构造方法");
    25     }
    26 
    27 }

    子类代码:

     1 public class Child extends Parent {
     2     public static int m = 26;
     3     private int n = 37;
     4 
     5     static {
     6         System.out.println("child 静态代码块,无静态变量");
     7     }
     8 
     9     static {
    10         m = m + 300;
    11         System.out.println("child 静态代码块,有静态变量,m=" + m);
    12     }
    13 
    14     {
    15         System.out.println("child 代码块,无静态变量");
    16     }
    17 
    18     {
    19         n = n + 400;
    20         System.out.println("child 代码块,有静态变量, n=" + n);
    21     }
    22 
    23     public Child(){
    24         System.out.println("child 构造方法");
    25     }
    26 
    27     public static void main(String[] args) {
    28         Child child = new Child();
    29     }
    30 }

    执行结果:

    parent 静态代码块,无静态变量
    parent 静态代码块,有静态变量,i=110
    child 静态代码块,无静态变量
    child 静态代码块,有静态变量,m=326
    parent 代码块,无静态变量
    parent 代码块,有静态变量,j=215
    parent 构造方法
    child 代码块,无静态变量
    child 代码块,有静态变量, n=437
    child 构造方法

    结论:

    1. 若存在继承关系,而且父类和子类中都存在静态代码块、静态变量、构造代码块、构造方法

    2. 先是父类静态代码块和静态变量,静态代码块和静态变量的初始化顺序 是谁在前谁先加载

    3. 再是子类静态代码块和静态变量,静态代码块和静态变量的初始化顺序 是谁在前谁先加载

    4. 再是父类构造代码块,父类构造方法

    5. 再是子类构造代码块,父类构造方法

  • 相关阅读:
    Mysql语句练习
    Mysql-------查询各科成绩前三名的记录
    Mysql--查询"01"课程比"02"课程成绩高的学生的信息及课程分数
    模态框拖拽案例分析--元素偏移量 offset 系列
    CSS中z-index的属性与使用
    《将博客搬至CSDN》
    CSS中Position几种属性的总结
    考研数学一
    ubuntu16.04安装mysql报错解决
    LoRaWAN 规范1.0 (章节10~13)
  • 原文地址:https://www.cnblogs.com/zhuitian/p/12104614.html
Copyright © 2011-2022 走看看