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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值