Java static 深入分析(一)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/helloworlddm/article/details/82288694

static变量是一个类变量。
static变量再类装载的时候进行初始化
多个实例的static变量会共享同一块内存区
请看下面简单demo:

package staticTest;

public class SingletonTest  extends Test{
    public static   SingletonTest sl = new  SingletonTest();

    static {

        System.out.println("Hello world");
    }
    {

        System.out.println("i am the son");
    }
    public SingletonTest() {

        System.out.println("My name is Burning");
    }
    public static void main(String[] args) {

            //new  SingletonTest();

    }

}

Test.java

package staticTest;

public class Test {
    //private Test   test = new Test("哈哈哈哈");
    static  {   
        System.out.println("I am  the  father");        
    }
        {

            System.out.println("i am the father");
        }

    public   Test() {

        System.out.println("constructor  of  father");
    }
    public   Test(String  str) {

            System.out.println(str);
    }


}

运行结果是:
这里写图片描述
分析下执行顺序:
(1)初始化父类的静态变量或者静态代码块
(2)初始化静态变量s1,执行new SingletonTest()
(3) 执行父类的初始化代码块
(4)执行父类的构造器
(5)执行子类的初始化代码块
(6)执行子类的构造器
(8)子类的静态初始化块

猜你喜欢

转载自blog.csdn.net/helloworlddm/article/details/82288694