问题描述
正如标题所说,两者究竟有什么区别
As the title says, what exactly is the difference between
public static String myString = "Hello World!";
和
public static String myString;
static {
myString = "Hello World";
}
除了结构之外还有什么重要的区别吗?
is there any important difference other than the structure ?
推荐答案
对于您的示例,没有区别.但正如你所看到的,
For your example, there is no difference. But as you can see,
public static String myString = "Hello World!";
只能接受一个表达式来初始化变量.但是,在 静态初始值设定项 (JLS 8.7),可以执行任意数量的语句.例如.可以这样做:
can only accept an expression to initialize the variable. However, in a static initializer (JLS 8.7), any number of statements may be executed. E.g. it's possible to do this:
static
{
myString = "Hello";
myString += " ";
myString += "World";
}
对于您的示例,显然没有必要这样做,但是变量的初始化可能需要的不仅仅是一个表达式,也许还有许多语句,因此 Java 制作了静态初始化程序.
For your example, there's obviously no need to do that, but it's possible for the initialization of a variable to take more than an expression, perhaps many statements, so Java made static initializers.
这篇关于静态初始化块和常规静态初始化的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!