zoukankan      html  css  js  c++  java
  • 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语句块和成员变量的初始化,最后再执行构造方法的内容

  • 相关阅读:
    P1383 高级打字机
    P1383 高级打字机
    P3723 [AH2017/HNOI2017]礼物 [FFT]
    P3723 [AH2017/HNOI2017]礼物 [FFT]
    P3338 [ZJOI2014]力 [FFT]
    P3338 [ZJOI2014]力 [FFT]
    P2597 [ZJOI2012]灾难
    c语言推箱子 扫雷项目
    蓝桥杯c语言基础题
    c语言的图形库
  • 原文地址:https://www.cnblogs.com/zemliu/p/2742727.html
Copyright © 2011-2022 走看看