How do I call one constructor from another in Java?

前端 未结 21 2526
不知归路
不知归路 2020-11-22 01:06

Is it possible to call a constructor from another (within the same class, not from a subclass)? If yes how? And what could be the best way to call another constructor (if th

21条回答
  •  误落风尘
    2020-11-22 01:19

    Originally from an anser by Mirko Klemm, slightly modified to address the question:

    Just for completeness: There is also the Instance initialization block that gets executed always and before any other constructor is called. It consists simply of a block of statements "{ ... }" somewhere in the body of your class definition. You can even have more than one. You can't call them, but they're like "shared constructor" code if you want to reuse some code across constructors, similar to calling methods.

    So in your case

    { 
      System.out.println("this is shared constructor code executed before the constructor");
      field1 = 3;
    }
    

    There is also a "static" version of this to initialize static members: "static { ... }"

提交回复
热议问题