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

前端 未结 3 1006
暖寄归人
暖寄归人 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:31

    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.

提交回复
热议问题