java - 为什么这个 Java 代码在方法之外的大括号 ({}) 中?

标签 java syntax braces

我正在为 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);  
    }  
}

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

最佳答案

借自 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.

您可能还想查看讨论 here .

关于java - 为什么这个 Java 代码在方法之外的大括号 ({}) 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5865069/

相关文章:

css - 自定义 .sass 的格式输出?

java - 从循环中获取数组元素

java - 除了修改 hadoop-env.sh 之外,如何在 hadoop 中指定系统属性?

java - 如何在 Android Studio 中添加 Snap to Roads Google Map

php - 检查 php-code w/o php-cli 的语法,可能吗?

mysql - SQL SELECT 来自多个表或 JOIN

mysql - 大括号显示mysql的结果

java - 如何在 apache TOMCAT 中安装/设置 php

python - 语法错误: Python for loop and if statement

C语言: if() with no else(): using braces fails