package com.jvm.init;
/**
* @author JTY
* @date 21-2-21 0:37
* @description 类的初始化过程
* 1. 父类 默认初始值 0 或null (jvm 中类构造器()方法)
* 2. 子类默认初始值 0 或null (jvm 中类构造器()方法)
* 3. 父类静态字段初始化
* 4. 静态代码块初始化 先父类再子类
* 5. 子类静态字段初始化
* 6. 普通字段(有赋值操作)初始化
* 7. 构造方法初始化 先父类再子类 (jvm 中实例构造器()方法)
*/
public class ClassInitOrder {
static class Father {
private String three = "3";
private static String one = "1";
public static String five = "5";
public Father() {
System.out.println("Father::" + three);
System.out.println("Father::" + "4");
//验证子类静态字段初始化在父类构造方法前执行
showFive();
}
static {
//验证子类中获取到的值为此处赋值的值
five = "6";
System.out.println("Father::" + one);
System.out.println("Father::" + "2");
System.out.println("Father::" + five);
}
public void showFive() {
}
;
}
static class Son extends Father {
private String three = "3";
private static String one = "1";
//验证子类字段初始化在父类静态块之后执行,赋值为6,在父类构造方法前执行,可通过动态分派访问该值确定已赋值为6
private static String five_5 = five;
public Son() {
System.out.println("Son::" + three);
System.out.println("Son::" + "4");
}
static {
System.out.println("Son::" + one);
System.out.println("Son::" + "2");
System.out.println("Son::" + five_5);
}
public void showFive() {
System.out.println("son::" + five_5);
}
;
}
public static void main(String[] args) {
/***
* 输出
----------
Father::1
Father::2 父类静态块
Father::6
Son::1 子类静态块
Son::2
Son::6
----------
Father::3 父类构造方法
Father::4
son::6
----------
Son::3 子类构造方法
Son::4
----------
*/
Son s = new Son();
}
}