为什么此 Java 代码位于方法外部的大括号 ({}) 中?
我正在准备 Java 认证考试,并且我在其中一个练习测试中看到了类似这样的代码:
class Foo {
int x = 1;
public static void main(String [] args) {
int x = 2;
Foo f = new Foo();
f.whatever();
}
{ x += x; } // <-- what's up with this?
void whatever() {
++x;
System.out.println(x);
}
}
我的问题是...在方法外部用花括号编写代码是否有效?这些影响是什么(如果有的话)?
I am getting ready for a java certification exam and I have seen code LIKE this in one of the practice tests:
class Foo {
int x = 1;
public static void main(String [] args) {
int x = 2;
Foo f = new Foo();
f.whatever();
}
{ x += x; } // <-- what's up with this?
void whatever() {
++x;
System.out.println(x);
}
}
My question is ... Is it valid to write code in curly braces outside a method? What are the effects of these (if any)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
借自此处 -
您可能还想查看此处的讨论。
Borrowed from here -
You may also wanna look at the discussions here.
这是一个初始化程序块,在加载/创建类的实例时执行,用于初始化类的成员属性(请参阅 Java http://download.oracle.com/javase/tutorial/java/javaOO/initial.html)。您可以拥有任意数量的块,它们将从上到下实例化。
除了实例块之外,您还可以拥有任意数量的静态块来初始化静态成员。它们将被声明如下:
当类被初始化时,静态成员“b”被初始化为10,然后第一个静态范围将其值更改为-9,稍后更改为1。这仅在类初始化时执行一次已加载。这在 main 方法的第一行初始化之前执行。
另一方面,与您的类类似的示例是实例引用“a”。 A 初始化为 5,然后实例块将其更新为 7,最后一个块更新为 8。正如预期的那样,静态成员在此代码中仅初始化一次,而实例块在每次创建新实例时都会执行。
此示例的输出为 1 8 1 8
This is an initializer block that is executed while the instance of the class is being loaded/created and that is used to initialize member properties of a class (See Java http://download.oracle.com/javase/tutorial/java/javaOO/initial.html). You can have as many blocks as you want and they will be instantiated from top to bottom.
In addition to the instance block, you can have as many static blocks as you want as well to initialize static members. They would be declared as follows:
While the class is being initialized, the static member "b" is initialized as 10, then the first static scope changes its value to -9, and later to 1. This is only executed once while the class is loaded. This executes before the initialization of the first line of the main method.
On the other hand, the similar example to your class is the instance reference "a". A is initialized as 5, then the instance block updates it to 7, and the last block to 8. As expected, the static members are only initialized once in this code, while the instance blocks are executed EVERY time you create a new instance.
The output to this example is 1 8 1 8
它是一个初始化块。它用于设置实例变量。在构造函数上使用初始化块的动机是为了防止编写冗余代码。 Java 编译器将块的内容复制到每个构造函数中。
It's an initializer block. It's used to set instance variables. The motivation to use initializer blocks over constructors is to prevent writing redundant code. The Java compiler copies the contents of the block into each constructor.