In Java, why have a code block with no keywords, just curly brackets

前端 未结 4 1059
感动是毒
感动是毒 2020-12-11 14:49

I\'m re-factoring some inherited code, but was stumped by the design decision and can\'t figure out the proper terms to google this. My predecessor would use blocks like thi

4条回答
  •  南笙
    南笙 (楼主)
    2020-12-11 15:09

    It's called an initializer block.

    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.

提交回复
热议问题