How do I call one constructor from another in Java?

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

    I will tell you an easy way

    There are two types of constructors:

    1. Default constructor
    2. Parameterized constructor

    I will explain in one Example

    class ConstructorDemo 
    {
          ConstructorDemo()//Default Constructor
          {
             System.out.println("D.constructor ");
          }
    
          ConstructorDemo(int k)//Parameterized constructor
          {
             this();//-------------(1)
             System.out.println("P.Constructor ="+k);       
          }
    
          public static void main(String[] args) 
          {
             //this(); error because "must be first statement in constructor
             new ConstructorDemo();//-------(2)
             ConstructorDemo g=new ConstructorDemo(3);---(3)    
           }
       }                  
    

    In the above example I showed 3 types of calling

    1. this() call to this must be first statement in constructor
    2. This is Name less Object. this automatically calls the default constructor. 3.This calls the Parameterized constructor.

    Note: this must be the first statement in the constructor.

提交回复
热议问题