为什么此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);  
    }  
}

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

最佳答案

从这里借来的-

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.

您可能也想在这里查看讨论。

    公众号
    关注公众号订阅更多技术干货!