静态变量初始化与不初始化的区别

来源:互联网 发布:阿里云虚拟主机优惠 编辑:程序博客网 时间:2024/05/15 04:22

1.无意间的一段程序代码引起了我研究的兴趣,之前对于Java的执行机制不是很透彻,为自己充充电.

public class test {private static test test = new  test();public static int count1;public static int count2=0;private test(){System.out.println("执行构造方法前count1=" + count1+ "    count2==" + count2);count1++;count2=9999;System.out.println("执行构造方法后count1=" + count1+ "    count2==" + count2);}public static test getTest(){return test;}public static void main(String[] args) {System.out.println("执行主方法count1=" + count1+ "    count2==" + count2);}}结果:执行构造方法前count1=0    count2==0执行构造方法后count1=1    count2==9999执行主方法count1=1    count2==0
这是一个单例模式,首先,由于第一句是private static test test = new test();所以在初始化静态变量test时中间插入了一个构造函数,造成了count1和count2最后的结果不一样。

执行顺序:

1.初始化静态变量,第一个赋值操作是(static)test = new test();JVM会调用构造函数,完成count1和count2的赋值。到此为止 count1=1,count2=9999;

2.执行private static test test = new test();进行类加载,初始化 count1 (已经是1),counter2(重新设置成0);

3.执行main方法。

2.当我改成下面后,结果又不一样了,因为在执行private static test test = new test();后,初始化 count1 (重新设置成0),count2(已经是9999)。

package com.isoftstone.epsp.web.portal.app;public class test {private static test test = new  test();public static int count1=0;//改变public static int count2;//改变private test(){System.out.println("执行构造方法前count1=" + count1+ "    count2==" + count2);count1++;count2=9999;System.out.println("执行构造方法后count1=" + count1+ "    count2==" + count2);}public static test getTest(){return test;}public static void main(String[] args) {System.out.println("执行主方法count1=" + count1+ "    count2==" + count2);}}结果:执行构造方法前count1=0    count2==0执行构造方法后count1=1    count2==9999执行主方法count1=0    count2==9999 

3.当我改变private static test test = new test();的位置后,因为执行private static test test = new test();后,这一句 public static int count1=0;没有执行,也就是count1没有被重新赋值,只会初始化count2(已经是9999)。

        public static int count1=0;private static test test = new  test();public static int count2;结果:执行构造方法前count1=0    count2==0执行构造方法后count1=1    count2==9999执行主方法count1=1    count2==9999

4。当我改变private static test test = new test();的位置后,因为执行private static test test = new test();后,前面count1和count2语句都没有执行,结果就是构造函数中运算的值。

    public static int count1=0;    public static int count2;    private static test test = new  test();结果:执行构造方法前count1=0    count2==0执行构造方法后count1=1    count2==9999执行主方法count1=1    count2==9999

总结:

对象的初始化顺序:首先执行父类静态的内容,父类静态的内容执行完毕后,接着去执行子类的静态的内容,当子类的静态内容执行完毕之后,再去看父类有没有非静态代码块,如果有就执行父类的非静态代码块,父类的非静态代码块执行完毕,接着执行父类的构造方法;父类的构造方法执行完毕之后,它接着去看子类有没有非静态代码块,如果有就执行子类的非静态代码块。子类的非静态代码块执行完毕再去执行子类的构造方法。总之一句话,静态代码块内容先执行,接着执行父类非静态代码块和构造方法,然后执行子类非静态代码块和构造方法。


0 0
原创粉丝点击