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

前端 未结 3 1009
暖寄归人
暖寄归人 2020-11-27 17:08

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 sta         


        
3条回答
  •  盖世英雄少女心
    2020-11-27 17:41

    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.

提交回复
热议问题