1.父类
/**
* @Description 父类子类实例化顺序
* @Author rll
* @Date 2021-01-07 14:44
*/
public class Father {
//静态代码块
static {
System.out.println("father static {}");//1
}
//静态字段
private static SayMsg msgSta = new SayMsg("father static Msg");//2
//普通代码块
{
System.out.println("father no static {}");//5
}
//普通字段
private SayMsg msg = new SayMsg("father Msg");//6
//构造器
public Father() {
System.out.println("father constructor");//7
}
}
2.子类
/**
* @Description 父类子类实例化顺序
* @Author rll
* @Date 2021-01-07 14:44
*/
public class Son extends Father {
//静态代码块
static {
System.out.println("son static{}"); //3
}
//静态字段
private static SayMsg msgSta = new SayMsg("son static Msg");//4
//普通代码块
{
System.out.println("son no static{}");//8
}
//普通字段
private SayMsg msg = new SayMsg("son Msg");//9
//构造器
public Son() {
System.out.println("son constructor");//10
}
public static void main(String[] args) {
Father s1 = new Son();
}
}
3.打印类
/**
* @Description 用来看谁先生成
* @Author rll
* @Date 2021-01-07 15:24
*/
public class SayMsg {
public SayMsg(String str){
System.out.println(str);
}
}
4.最终输出内容
father static {}
father static Msg
son static{}
son static Msg
father no static {}
father Msg
father constructor
son no static{}
son Msg
son constructor
相应的输出顺序也在代码中标出。
上述代码打印顺序依次是:1父类静态模块,2父类静态字段, 3子类静态模块,4子类静态字段,5父类非静态模块,6父类非静态字段,7父类构造器,8子类非静态模块,9子类非静态字段,10子类构造器
注意:类中静态模块和静态字段的顺序看你把谁先声明,可自己调换位置尝试
5.java编程思想中的例子改
/**
* @Description 编程思想实例化顺序改
* @Author rll
* @Date 2021-01-11 10:52
*/
class Insect
{
private int i = 9;
protected static int j;
public Insect()
{
Print.print("Insect constructor \n i = " + i + ",j = " + j);
j = 39;
}
private static int x1 = printInit("static Insect.x1 初始化");
static int printInit(String s)
{
Print.print(s);
return 47;
}
}
public class Beetle extends Insect
{
private int k = printInit("Beetle.k 初始化");
public Beetle()
{
Print.print("Beetle constructor \n k = " + k);
Print.print("j = " + j);
}
private static int x2 = printInit("static Beetle.x2 初始化");
public static void main(String[] args)
{
// Print.print("Beetle constructor");
Beetle a= new Beetle();
}
}
/* 旧输出
static Insect.x1 初始化
static Beetle.x2 初始化
Beetle constructor
i = 9,j = 0
Beetle.k 初始化
k = 47
j = 39
i = 9,j = 39
新输出
static Insect.x1 初始化
static Beetle.x2 初始化
Insect constructor
i = 9,j = 0
Beetle.k 初始化
Beetle constructor
k = 47
j = 39
*///:~
书中这个例子的输出很容易让人误解,所以我在构造器输出中加入输出constructor,结果是一致的, constructor是最后实例化的。