public class Person
{
{
a = 6;
//if (a > 4)
{
System.out.println("Person init block a > 4");
}
}
public int a = 9;
{
System.out.println("second executed");
}
static {//即使不实例化对象也会执行
System.out.println("Person static block");
}
public static void main(String[] args)
{
//Person p = new Person();
//System.out.println(" a " + p.a);
Leaf l = new Leaf();
Leaf ll = new Leaf();
}
}
class Root
{
static{
System.out.println("root static init");
}
{
System.out.println("root normal init");
}
public Root()
{
System.out.println("root constructor");
}
}
class Mid extends Root
{
static{
System.out.println("mid static init");
}
{
System.out.println("mid normal init");
}
public Mid()
{
System.out.println("mid constructor");
}
}
class Leaf extends Mid
{
static{
System.out.println("Leaf static init");
}
{
System.out.println("Leaf normal init");
}
public Leaf()
{
System.out.println("Leaf constructor");
}
}
输出结果为:
Person static block
root static init
mid static init
Leaf static init
root normal init
root constructor
mid normal init
mid constructor
Leaf normal init
Leaf constructor
root normal init
root constructor
mid normal init
mid constructor
Leaf normal init
Leaf constructor
初始化 顺序 :
静态 初始化块(父类 ---> 子类 )---->父类 的 非静态的初始化块(声明属性实例默认值 (由初始化块和默认值定义声明的顺序决定执行顺序 )) -----> 父类的构造函数 -------> 子类的非静态的初始化块 (声明属性实例默认值 (由初始化块和默认值定义声明的顺序决定执行顺序 )) ---------> 子类的构造函数
本文详细解析了Java中类的初始化顺序,包括静态初始化块、非静态初始化块及构造函数的执行顺序,并通过具体示例代码展示了从父类到子类的完整执行流程。

被折叠的 条评论
为什么被折叠?



