欢迎来到天天文库
浏览记录
ID:57651534
大小:28.50 KB
页数:8页
时间:2020-08-30
《学习java静态数据初始化.doc》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、Static数据的初始化(注意结合代码调试理解):packagecom.initialization.order;classBowl{ Bowl(){ System.out.println("Bowl(9)"); } Bowl(intmarker){ System.out.println("Bowl("+marker+")"); } staticBowlb6=newBowl(6); staticBowlb9=newBowl(); voidf(intmarker){ Sy
2、stem.out.println("f("+marker+")"); } }classTable{ staticBowlb1=newBowl(1); Table(){ System.out.println("Table()"); b2.f(1); } voidf2(intmarker){ System.out.println("f2("+marker+")"); } staticBowlb2=newBowl(2);}classCupboard{ Bowlb3=newBowl(3); Bowlb10
3、=newBowl(); staticBowlb4=newBowl(4); Cupboard(){ System.out.println("Cupboard()"); b4.f(2); } voidf3(intmarker){ System.out.println("f3("+marker+")"); } staticBowlb5=newBowl(5);}publicclassStaticInitialization{ //staticBowlb7=newBowl(7);
4、 //----------(1) publicstaticvoidmain(String[]args){ System.out.println( "CreatingnewCupboard()inmain"); newCupboard(); System.out.println( "CreatingnewCupboard()inmain"); newCupboard(); //t2.f2(1); //---
5、-----------(2) //t3.f3(1); //---------------(3) } //staticBowlb8=newBowl(8); //----------------(4) //staticTablet2=newTable(); //----------------(5) //staticCupboardt3=newCupboard(); //---------(6)}///:~调试以上代码,总结出以下结论:一、初始化的过
6、程:总体来说顺序为:static初始化->非static初始化->执行构造函数;二、代码分析一:对现有代码执行结果如下:CreatingnewCupboard()inmainBowl(6)Bowl(9)Bowl(4)Bowl(5)Bowl(3)Bowl(9)Cupboard()f(2)CreatingnewCupboard()inmainBowl(3)Bowl(9)Cupboard()f(2)执行过程: 1、java解释器寻找publicclass类,加载StaticInitialization
7、类; 2、寻找StaticInitialization 类中的static定义代码段;这里因为(1)、(4)、(5)、(6)均加了注释,所以StaticInitialization 中没有static需要初始化; 3、进入main函数中执行代码输出CreatingnewCupboard()inmain; 4、继续执行newCupboard();,注意初始化的顺序是static初始化->非static初始化->执行构造函数;所以加载类Cupboard后,首先寻找Cupboa
8、rd类中的static代码段;发现static段是: staticBowlb4=newBowl(4);staticBowlb5=newBowl(5);同时发现有非static段是: Bowlb3=newBowl(3); Bowlb10=newBowl(); 按顺序先执行:staticBowlb4=newBowl(4);初始化,因为定义的是Bowl类的实例,所以先加载B
此文档下载收益归作者所有