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

发布于 2024-11-04 20:36:57 字数 414 浏览 2 评论 0原文

我正在准备 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

葬心 2024-11-11 20:36:57

借自此处 -

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

<前><代码>{
// 初始化所需的任何代码都放在这里
}

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

您可能还想查看此处的讨论

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.

You may also wanna look at the discussions here.

ι不睡觉的鱼゛ 2024-11-11 20:36:57

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

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

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++;
    }
}

当类被初始化时,静态成员“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:

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.

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

煞人兵器 2024-11-11 20:36:57

它是一个初始化块。它用于设置实例变量。在构造函数上使用初始化块的动机是为了防止编写冗余代码。 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文