zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    洛谷 P5057 [CQOI2006]简单题 题解
    洛谷 P3368 【模板】树状数组 2 题解
    洛谷 P3374 【模板】树状数组 1 题解
    洛谷 P2023 [AHOI2009]维护序列 题解
    洛谷 P2253 好一个一中腰鼓! 题解
    求最长不下降/上升/下降/不上升子序列
    [SQL Server]Index/deadlock
    Ubuntu 14.04下从源码安装qt4.x
    Ubuntu系统下Import cv2提示no modules ...错误
    Ubuntu 14.04下安装CUDA8.0
  • 原文地址:https://www.cnblogs.com/liujinhong/p/6505325.html
Copyright © 2011-2022 走看看