分类:
java(8)
版权声明:本文为博主原创文章,未经博主允许不得转载。
- package Study.Initialization;
- class Base{
- private String str1=init("str1");
- private String str2=init("str2");
- public static String str3=init("static str3");
- public Base(String str1,String str2){
- System.out.println("Run Construction Base");
- this.str1=str1;
- this.str2=str2;
- }
- protected static String init(String str){
- System.out.println(str);
- return str+" init";
- }
- }
- class Derived extends Base{
- private String str4=init("str4");
- public static String str5=init("static str5");
- public Derived(String str1,String str2,String str4){
- super(str1,str2);
- System.out.println("Run Construction Derived");
- this.str4=str4;
- }
- }
- public class extendInitialization {
- public static void main(String[] args) {
- System.out.println("run extendInitialization.main()");
- Derived d=new Derived("construction str1","construction str2","construction str4");
- System.out.println("----------------------------------------");
- Derived d2=new Derived("construction str11","construction str22","construction str44");
- }
- }
运行结果:
run extendInitialization.main()
static str3
static str5
str1
str2
Run Construction Base
str4
Run Construction Derived
----------------------------------------
str1
str2
Run Construction Base
str4
Run Construction Derived
总结:
Derived的初始化顺序:
1.按定义时的顺序初始化基类的static成员
2..按定义时的顺序初始化扩展类的static成员
(以上两条是对第一次定义扩展类对象时运行)
3.按定义时顺序执行基类的指定初始化
4.执行基类的构造函数
5 按定义时的顺序执行扩展类的指定初始化
6.行扩展类的构造函数