您的位置:首页 > 编程语言 > Java开发

java中父类和子类初始化顺序

2016-11-09 23:39 387 查看

顺序

1. 父类中静态成员变量和静态代码块

2. 子类中静态成员变量和静态代码块

3. 父类中普通成员变量和代码块,父类的构造函数

4. 子类中普通成员变量和代码块,子类的构造函数

其中“和”字两端的按照代码先后顺序执行。

举例

先看代码:

Father类

public class Father {
public String fStr1 = "father1";
protected String fStr2 = "father2";
private String fStr3 = "father3";

{
System.out.println("Father common block be called");
}

static {
System.out.println("Father static block be called");
}

public Father() {
System.out.println("Father constructor be called");
}

}
首先是Father类,该类有一个默认构造函数,有一个static的代码块,为了方便查看结果,还有一个普通代码块。

Son类

package com.zhenghuiyan.testorder;

public class Son extends Father{
public String SStr1 = "Son1";
protected String SStr2 = "Son2";
private String SStr3 = "Son3";

{
System.out.println("Son common block be called");
}

static {
System.out.println("Son static block be called");
}

public Son() {
System.out.println("Son constructor be called");
}

public static void main(String[] args) {
new Son();
System.out.println();
new Son();
}

}

Son类的内容与Father类基本一致,不同在于Son继承自Father。该类有一个main函数,仅为了测试用,不影响结果。

在main函数中实例化Son。

结果为:

Father static block be called
Son static block be called
Father common block be called
Father constructor be called
Son common block be called
Son constructor be called

Father common block be called
Father constructor be called
Son common block be called
Son constructor be called


总结:

1,在类加载的时候执行父类的static代码块,并且只执行一次(因为类只加载一次);

2,执行子类的static代码块,并且只执行一次(因为类只加载一次);

3,执行父类的类成员初始化,并且是从上往下按出现顺序执行(在debug时可以看出)。

4,执行父类的构造函数;

5,执行子类的类成员初始化,并且是从上往下按出现顺序执行。

6,执行子类的构造函数。

欢迎转载,请标明出处:http://blog.csdn.net/yuxin6866/article/details/53107578
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息