How do I call one constructor from another in Java?

前端 未结 21 2890
不知归路
不知归路 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:15

    It is called Telescoping Constructor anti-pattern or constructor chaining. Yes, you can definitely do. I see many examples above and I want to add by saying that if you know that you need only two or three constructor, it might be ok. But if you need more, please try to use different design pattern like Builder pattern. As for example:

     public Omar(){};
     public Omar(a){};
     public Omar(a,b){};
     public Omar(a,b,c){};
     public Omar(a,b,c,d){};
     ...
    

    You may need more. Builder pattern would be a great solution in this case. Here is an article, it might be helpful https://medium.com/@modestofiguereo/design-patterns-2-the-builder-pattern-and-the-telescoping-constructor-anti-pattern-60a33de7522e

提交回复
热议问题