How do I call one constructor from another in Java?

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

    You can a constructor from another constructor of same class by using "this" keyword. Example -

    class This1
    {
        This1()
        {
            this("Hello");
            System.out.println("Default constructor..");
        }
        This1(int a)
        {
            this();
            System.out.println("int as arg constructor.."); 
        }
        This1(String s)
        {
            System.out.println("string as arg constructor..");  
        }
    
        public static void main(String args[])
        {
            new This1(100);
        }
    }
    

    Output - string as arg constructor.. Default constructor.. int as arg constructor..

提交回复
热议问题