Java:静态初始化块什么时候有用? [英] Java: When is a static initialization block useful?
本文介绍了Java:静态初始化块什么时候有用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
static
块中的初始化之间有什么区别?
What's the difference between initialization within a static
block:
public class staticTest {
static String s;
static int n;
static double d;
static {
s = "I'm static";
n = 500;
d = 4000.0001;
}
...
以及单个静态初始化:
public class staticTest {
static String s = "I'm static";
static int n = 500;
static double d = 4000.0001;
....
推荐答案
静态初始化块允许更复杂的初始化,例如,使用条件语句:
A static initialization blocks allows more complex initialization, for example using conditionals:
static double a;
static {
if (SomeCondition) {
a = 0;
} else {
a = 1;
}
}
或者需要的不仅仅是构造:使用构建器创建实例时,除了创建静态字段之外,还必须进行异常处理或其他工作.
Or when more than just construction is required: when using a builder to create your instance, exception handling or work other than creating static fields is necessary.
静态初始化块也在内联静态初始化器之后运行,因此以下内容是有效的:
A static initialization block also runs after the inline static initializers, so the following is valid:
static double a;
static double b = 1;
static {
a = b * 4; // Evaluates to 4
}
这篇关于Java:静态初始化块什么时候有用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文