2.查看此类是否为启动运行类,若为启动运行类,则执行main()方法里的语句对应语句 3.若不是启动运行类,则按代码的排版先后顺序继续执行非static element的变量赋值以及代码块.
觉得core java在java 初始化过程的总体顺序没有讲,只是说了构造器时的顺序,作者似乎认为路径很多,列出来比较混乱。我觉得还是要搞清楚它的过程比较好。所以现在结合我的学习经验写出具体过程:
过程如下:
1.在类的声明里查看有无静态元素(static element, 我姑且这么叫吧),比如:
static int x = 1, { //block float sss = 333.3; string str = "hello"; } 或者 比如 static { //(static block), int x = 2; double y = 33.3; } |
2.查看此类是否为启动运行类,若为启动运行类,则执行main()方法里的语句对应语句
3.若不是启动运行类,则按代码的排版先后顺序继续执行非static element的变量赋值以及代码块.
4.最后执行构造方法,如果在被调用的构造方法里面有this关键字(注意,如果你考虑要调用其他构造方法,则应该把this写在最前面,不然会产生错误),则先调用相应构造方法主体,调用完之后再执行自己的剩下语句.
/** *//** * * @author livahu * created on 2006年9月6日, 下午17:00 */ class firstclass ...{ firstclass(int i) ...{ system.out.println("firstclass(" + i + ")"); } void usemethod(int k) ...{ system.out.println("usemethod(" + k + ")"); } } class secondclass ...{ static firstclass fc1 = new firstclass(1); firstclass fc3 = new firstclass(3); static ...{ firstclass fc2 = new firstclass(2); } ...{ system.out.println("secondclass's block, this block is not static block."); } secondclass() ...{ system.out.println("secondclass()"); } firstclass fc4 = new firstclass(4); } public class initiationdemo ...{ secondclass sc1 = new secondclass(); ...{ system.out.println("hello java world!"); } public static void main(string[] args) ...{ system.out.println("inside main()"); secondclass.fc1.usemethod(100); initiationdemo idobj = new initiationdemo(); } static secondclass sc2 = new secondclass(); } |
运行结果:
firstclass(1) firstclass(2) firstclass(3) secondclass's block, this block is not static block. firstclass(4) secondclass() inside main() usemethod(100) firstclass(3) secondclass's block, this block is not static block. firstclass(4) secondclass() hello java world! |