为什么此 Java 代码位于方法外部的大括号 ({}) 中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5865069/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 13:11:23  来源:igfitidea点击:

Why is this Java code in curly braces ({}) outside of a method?

javasyntaxbraces

提问by nairdaen

I am getting ready for a java certification exam and I have seen code LIKE this in one of the practice tests:

我正准备参加 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);  
    }  
}

My question is ... Is it valid to write code in curly braces outside a method? What are the effects of these (if any)?

我的问题是......在方法外用花括号编写代码是否有效?这些(如果有的话)有什么影响?

回答by Shankar Raju

Borrowed from here-

这里借来的——

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
} 

The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.

通常,您会在构造函数中放置用于初始化实例变量的代码。使用构造函数初始化实例变量有两种替代方法:初始化块和最终方法。实例变量的初始化块看起来就像静态初始化块,但没有 static 关键字:

{
    // whatever code is needed for initialization goes here
} 

Java 编译器将初始化块复制到每个构造函数中。因此,这种方法可用于在多个构造函数之间共享代码块。

You may also wanna look at the discussions here.

您可能还想查看这里的讨论。

回答by Marcello de Sales

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.

这是一个初始化块,在加载/创建类的实例时执行,用于初始化类的成员属性(参见 Java http://download.oracle.com/javase/tutorial/java/javaOO /initial.html)。您可以根据需要拥有任意数量的块,它们将从上到下进行实例化。

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:

除了实例块之外,您还可以拥有任意数量的静态块来初始化静态成员。它们将被声明如下:

public class Initialization {

    static int b = 10;

    int a = 5;

    static {
        b = -9;
    }

    {
        a += 2;
    }

    public static void main(String[] args) throws Exception {

        System.out.println(ClientVoting.b);
        System.out.println(new ClientVoting().a);
        System.out.println(ClientVoting.b);
        System.out.println(new ClientVoting().a);

    }

    static {
        b = 1;
    }

    {
        a++;
    }
}

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.

当类被初始化时,静态成员“b”被初始化为 10,然后第一个静态范围将其值更改为 -9,然后更改为 1。这仅在类加载时执行一次。这在 main 方法的第一行初始化之前执行。

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.

另一方面,与您的类类似的示例是实例引用“a”。A 初始化为 5,然后实例块将其更新为 7,最后一个块更新为 8。正如预期的那样,静态成员在这段代码中只初始化一次,而实例块在每次创建新实例时都会执行。

The output to this example is 1 8 1 8

这个例子的输出是 1 8 1 8

回答by blackcompe

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.

这是一个初始化块。它用于设置实例变量。在构造函数上使用初始化块的动机是为了防止编写冗余代码。Java 编译器将块的内容复制到每个构造函数中。