Java 静态(static)与非静态语句执行顺序

Java中的静态(static)关键字只能用于成员变量或语句块,不能用于局部变量

static 语句的执行时机实在第一次加载类信息的时候(如调用类的静态方法,访问静态成员,或者调用构造函数), static 语句和 static 成员变量的初始化会先于其他语句执行,而且只会在加载类信息的时候执行一次,以后再访问该类或new新对象都不会执行

而非 static 语句或成员变量,其执行顺序在static语句执行之后,而在构造方法执行之前,总的来说他们的顺序如下

1. 父类的 static 语句和 static 成员变量

2. 子类的 static 语句和 static 成员变量

3. 父类的 非 static 语句块和 非 static 成员变量

4. 父类的构造方法

5. 子类的 非 static 语句块和 非 static 成员变量

6. 子类的构造方法

参见如下例子

Bell.java

public class Bell {
    public Bell(int i) {
        System.out.println("bell " + i + ": ding ling ding ling...");
    }
}

Dog.java

public class Dog {
    // static statement
    static String name = "Bill";

    static {
        System.out.println("static statement executed");
    }

    static Bell bell = new Bell(1);

    // normal statement
    {
        System.out.println("normal statement executed");
    }

    Bell bell2 = new Bell(2);

    static void shout() {
        System.out.println("a dog is shouting");
    }

    public Dog() {
        System.out.println("a new dog created");
    }
}

Test.java

public class Test {
    public static void main(String[] args) {
        // static int a = 1; this statement will lead to error
        System.out.println(Dog.name);
        Dog.shout();    // static statement would execute when Dog.class info loaded
        System.out.println();
        new Dog();  // normal statement would execute when construct method invoked
        new Dog();
    }
}

程序输出:

static statement executed
bell 1: ding ling ding ling...
Bill
a dog is shouting

normal statement executed
bell 2: ding ling ding ling...
a new dog created
normal statement executed
bell 2: ding ling ding ling...
a new dog created

可见第一次访问Dog类的static成员变量name时,static语句块和成员变量都会初始化一次,并且在以后调用static方法shout()或构造方法时,static语句块及成员变量不会再次被加载

而调用new Dog()构造方法时,先执非static语句块和成员变量的初始化,最后再执行构造方法的内容

原文地址:https://www.cnblogs.com/zemliu/p/2742727.html