What's the difference between an instance initializer and a constructor?

前端 未结 3 1872
走了就别回头了
走了就别回头了 2020-12-10 01:19

Just wondering about the reason of compiling code like this:

class MyClass extends AnotherClass {
  {
    MySecondClass object = new MySecondClass();
    obj         


        
3条回答
  •  醉酒成梦
    2020-12-10 02:05

    This is an instance initialization block that runs before the constructor and if you ask why would one wanna use it in place of the constructor? The answer is no, you don't.

    Just wondering about the reason of compiling code like this:

    You usually use it to factor out common code when using constructor overloading. So, the "the" above actually refers to one of the overloaded constructors that gets called on object instantiation after the common instance initialization code block has executed.

    By the way, you could sometimes achieve the same by calling one constructor from the other but the call then has to be on the first line inside the calling constructor or the code won't compile.

提交回复
热议问题