How do I call one constructor from another in Java?

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

    There are design patterns that cover the need for complex construction - if it can't be done succinctly, create a factory method or a factory class.

    With the latest java and the addition of lambdas, it is easy to create a constructor which can accept any initialization code you desire.

    class LambdaInitedClass {
    
       public LamdaInitedClass(Consumer init) {
           init.accept(this);
       }
    }
    

    Call it with...

     new LambdaInitedClass(l -> { // init l any way you want });
    

提交回复
热议问题