Constructor Overloading in Java


☞A process of using a number of constructors with the same name but different types of parameter lists is known as constructor overloading.

☞The compiler differentiates these constructors by taking into account the number of parameters in the list and their type.

Example

class Area{
    
    int length;
    int breadth;

    Area(int l){
        length=l;
    }
    
    Area(int l, int b){
        length=l;
        breadth=b;
    }
    
    void display1(){
        System.out.println(length*length);
    }

    void display2(){
        System.out.println(length*breadth);
    }
    
    public static void main(String args[]){
    
        Area square = new Area(3);
        Area rectangle = new Area(4,5);
        square.display1();
        rectangle.display2();
        
    }
    
}

Output

9
20