• Java对象的初始化顺序


    new一个对象时,该对象的初始化顺序如下 :

    父类中的静态成员变量
    父类中的静态代码块
    子类中的静态成员变量
    子类中的静态代码块
    父类中的非静态变量
    父类中的非静态代码块
    父类构造函数
    子类中的非静态成员变量
    子类中的非静态代码块
    子类构造函数

    看如下例子(根据上面的初始化顺序,猜一下输出的顺序)

    class Money {
    public Money() {
    System.out.println("money");
    }
    }

    class Father {
    public static int age = 30;
    public Money m = new Money();
    public String name = "father";

    public Father() {
    System.out.println("father constructor start");
    System.out.println(age);
    age += 5;
    System.out.println(age);
    System.out.println("father constructor end");
    }

    static {
    System.out.println("father static block start");
    System.out.println(age);
    age += 5;
    System.out.println(age);
    System.out.println("father static block end");
    }
    }

    class Son extends Father {
    public Money m = new Money();
    public static int age = 10;
    public String name = "son";

    public Son() {
    System.out.println("son constructor start");
    System.out.println(age);
    age += 5;
    System.out.println(age);
    System.out.println("son constructor end");
    }

    static {
    System.out.println("son static block start");
    System.out.println(age);
    age += 5;
    System.out.println(age);
    System.out.println("son static block end");
    }
    }

    output:

    father static block start
    30
    35
    father static block end
    son static block start
    10
    15
    son static block end
    money
    father constructor start
    35
    40
    father constructor end
    money
    son constructor start
    15
    20
    son constructor end

  • 相关阅读:
    计算机的组成与操作系统
    面向对象初识
    规范化目录
    装饰器进阶
    装饰器练习
    装饰器
    内置函数二 闭包
    生成器 推导式 练习
    迭代器 递归 格式化 练习
    生成器 推导式 内置函数
  • 原文地址:https://www.cnblogs.com/liujinhong/p/6505325.html
Copyright © 2020-2023  润新知