How do I call one constructor from another in Java?

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

    Yes it is possible to call one constructor from another with use of this()

    class Example{
       private int a = 1;
       Example(){
            this(5); //here another constructor called based on constructor argument
            System.out.println("number a is "+a);   
       }
       Example(int b){
            System.out.println("number b is "+b);
       }
    

提交回复
热议问题