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

前端 未结 4 1039
感动是毒
感动是毒 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.

    0 讨论(0)
  • 2020-12-11 15:21

    It is an initializer block. (Related to static initializer block) See Initializing Instance Members on this page:

    http://download.oracle.com/javase/tutorial/java/javaOO/initial.html

    It is an alternative to a constructor. You could use it when providing multiple, overloaded constructors as a way to share code.

    Personally, however, I find it much clearer to have the constructor call a named initializer method rather than rely on the anonymous code block. Although, the compiler does copy the initializer block to all constructors behind the scenes and you could argue that there is a performance increase similar to inline'ing a method declaration.

    0 讨论(0)
  • 2020-12-11 15:33

    Scope. Any variables declared in the block go out of scope after the block. It's useful to keep variables scoped minimally.

    Also, if you define an anonymous inner class, you use this syntax for the constructor.

    0 讨论(0)
  • 2020-12-11 15:34

    Your predecessor was still learning.

    That's the best explanation you're likely to get. Perhaps at one point in time there was a need to have the code split up like this. It's hard to say. The code should certainly be written like this instead:

    public class ChildClass extends ParentClass {
        public ChildClass() {
            inheritedVar = "someVal";
        }
        // rest of code
    }
    

    As for the initializer block, its purpose has been given by the other answers here. I threw my answer in as an attempt to answer the "why", which you requested. Unfortunately, for the real answer, you would have to ask your predecessor.

    0 讨论(0)
提交回复
热议问题