为什么此 Java 代码位于方法外部的大括号 ({}) 中? [英] Why is this Java code in curly braces ({}) outside of a method?
问题描述
我正在为 Java 认证考试做准备,我在其中一个练习测试中看到过类似这样的代码:
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)?
推荐答案
借用 这里 -
通常情况下,您会将用于初始化实例变量的代码放在构造函数.使用构造函数有两种选择初始化实例变量:初始化块和最终方法.实例变量的初始化块看起来就像静态的初始化块,但没有 static 关键字:
Normally, you would put code to initialize an instance variable in a constructor. There are two alternatives to using a constructor to initialize instance variables: initializer blocks and final methods. Initializer blocks for instance variables look just like static initializer blocks, but without the static keyword:
{
// whatever code is needed for initialization goes here
}
Java 编译器将初始化块复制到每个构造函数中.因此,这种方法可以用于在多个构造函数之间共享一个代码块.
The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.
您可能还想查看此处的讨论.
这篇关于为什么此 Java 代码位于方法外部的大括号 ({}) 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!