Java初始化顺序
先看一个例子:
/**类A**/
class TestA {
public TestA(String a){
System.out.println(a);
}
}
/**类B**/
class TestB {
public TestB(String b){
System.out.println(b);
}
}
/**类 Parent **/
class Parent {
private static TestA testA1 = new TestA("Parent的静态变量");
static {
System.out.println("Parent的静态初始化模块");
}
private TestA testA2 = new TestA("Parent变量");
{
System.out.println("Parent的初始化模块");
}
public Parent(){
System.out.println("Parent的构造函数");
}
}
/**Parent的子类SubClass**/
public class SubClass extends Parent{
private static TestA testA1 = new TestA("SubClass的静态变量1");
static {
System.out.println("SubClass的静态初始化模块1");
}
private static TestA testA2 = new TestA("SubClass的静态变量2");
static {
System.out.println("SubClass的静态初始化模块2");
}
private TestA testA3 = new TestA("SubClass变量1");
{
System.out.println("SubClass的初始化模块1");
}
private TestA testA4 = new TestA("SubClass变量2");
{
System.out.println("SubClass的初始化模块2");
}
public SubClass(){
System.out.println("SubClass的构造函数");
}
public static void main(String[] args) {
SubClass subClass = new SubClass();
}
}
输出结果:
Parent的静态变量
Parent的静态初始化模块
SubClass的静态变量1
SubClass的静态初始化模块1
SubClass的静态变量2
SubClass的静态初始化模块2
Parent变量
Parent的初始化模块
Parent的构造函数
SubClass变量1
SubClass的初始化模块1
SubClass变量2
SubClass的初始化模块2
SubClass的构造函数
总结:
Java初始化的顺序如下:
父类静态初始化---->子类静态初始化---->父类初始化块---->父类构造方法---->子类初始化块---->子类构造
阅读(1465) | 评论(0) | 转发(0) |