静态修饰符和静态块之间的区别 [英] Difference between static modifier and static block

查看:159
本文介绍了静态修饰符和静态块之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人向我解释了以下两个陈述之间的区别吗?

Someone explain to me the differences between the following two statements?

一个静态最终变量由a初始化 static 代码块:

A static final variable initialized by a static code block:

private static final String foo;
static { foo = "foo"; }

由一个初始化的静态最终变量赋值:

A static final variable initialized by an assignment:

private static final String foo = "foo";


推荐答案

在这个例子中,有一个微妙的差异 - 在您的第一个示例中, foo 未确定为编译时常量,因此不能用作<$ c中的大小写$ c>切换块(并且不会内联到其他代码中);在你的第二个例子中,它是。例如:

In this example, there's one subtle difference - in your first example, foo isn't determined to be a compile-time constant, so it can't be used as a case in switch blocks (and wouldn't be inlined into other code); in your second example it, is. So for example:

switch (args[0]) {
    case foo:
        System.out.println("Yes");
        break;
}

foo 被认为是一个常量表达式,但不是当它只是一个静态的最终变量时。

That's valid when foo is deemed to be a constant expression, but not when it's "just" a static final variable.

但是,静态初始化程序块通常是当您有更复杂的初始化代码时使用 - 例如填充集合。

However, static initializer blocks are usually used when you have more complicated initialization code - such as populating a collection.

初始化的计时 JLS 12.4.2 ;任何被认为是编译时常量的静态最终字段首先被初始化(步骤6)并且初始化器被稍后运行(步骤9);所有初始化程序(无论它们是字段初始化程序还是静态初始化程序)都以文本顺序运行。

The timing for initialization is described in JLS 12.4.2; any static final fields which are considered as compile-time constants are initialized first (step 6) and initializers are run later (step 9); all initializers (whether they're field initializers or static initializers) are run in textual order.

这篇关于静态修饰符和静态块之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆