作者:青大柠的小号_247 | 来源:互联网 | 2023-10-12 20:31
一个类中的数据初始化顺序是面试官非常喜欢出的面试题之一,本文用一个实例来介绍java中子类、父类中静态代码块、字段,非静态代码块、字段以及构造函数的执行顺序和次数。一、包结构Cat
一个类中的数据初始化顺序是面试官非常喜欢出的面试题之一,本文用一个实例来介绍java中子类、父类中静态代码块、字段,非静态代码块、字段以及构造函数的执行顺序和次数。
一、包结构
Cat继承Animal
Runner里包含main函数,程序入口
Sing类主要用来打印执行顺序的序列号
二、代码
public class Animal {
Sing s1=new Sing(1,"animal\tnot static field");
static Sing s2=new Sing(2,"animal\tstatic field");
static Sing s3;
Sing s4;
Sing s5;
static{
s3=new Sing(3,"animal\tstatic code area");
}
{
s4=new Sing(4,"animal\tnot static code area");
}
Animal(){
s5=new Sing(5,"animal\tconstructor");
}
}
public class Cat extends Animal {
Sing s1=new Sing(1,"cat\t\tnot static field");
static Sing s2=new Sing(2,"cat\t\tstatic field");
static Sing s3;
Sing s4;
Sing s5; static{
s3=new Sing(3,"cat\t\tstatic code area");
} {
s4=new Sing(4,"cat\t\tnot static code area");
} Cat(){
s5=new Sing(5,"cat\t\tconstructor");
}
}
public class Sing {
Sing(int mark,String flag){
System.out.println(mark+" "+flag);
}
}
public class Runner {
public static void main(String[] args) {
System.out.println("+++++++++++++++++++++first+++++++++++++++++++++++++++++");
new Cat();
System.out.println("+++++++++++++++++++++second++++++++++++++++++++++++++++");
new Cat();
}
}
三、执行结果
+++++++++++++++++++++first+++++++++++++++++++++++++++++
2 animal static field
3 animal static code area
2 cat static field
3 cat static code area
1 animal not static field
4 animal not static code area
5 animal constructor
1 cat not static field
4 cat not static code area
5 cat constructor
+++++++++++++++++++++second++++++++++++++++++++++++++++
1 animal not static field
4 animal not static code area
5 animal constructor
1 cat not static field
4 cat not static code area
5 cat constructor
四、总结
初始化顺序:父类静态字段-》父类静态代码块-》子类静态字段-》子类静态代码块-》父类非静态字段-》父类非静态代码块-》父类构造-》子类非静态字段-》子类非静态代码块-》子类构造
遵循以下原则:
1、静态>非静态
2、父类>子类
3、字段>代码块>构造函数
4、静态字段、静态代码块在程序生命周期只初始化一次
转:https://www.cnblogs.com/2333/p/5736015.html