Calculate area of rectangle using constructor overloading in java

Let’s learn calculate area of rectangle using constructor overloading in java.

Calculate area of rectangle using constructor overloading in java

Constructor overloading is nothing but class having more than one constructor with same name but with different number of arguments.

calculate area of rectangle using constructor overloading in java

Java compiler determines constructor based on number and type of arguments we pass to constructor.

Also read – java program to find area of rectangle using parameterized constructor

Let’s see java program to find area of rectangle using constructor overloading.

import java.util.*;
class RectangleShape
{
   int length, breadth;
   // rectangle constructor java
   RectangleShape(int l, int b) 
   { 
      length = l; 
      breadth = b; 
   } 
   RectangleShape(int l) 
   { 
      length = l; 
      breadth = 20; 
   } 
   RectangleShape() 
   { 
      length = 6; 
      breadth = 2; 
   } 
   float getArea() 
   { 
      return(length * breadth); 
   }
}
public class FindArea 
{
   public static void main(String[] args)
   {
      RectangleShape rs1 = new RectangleShape(); 
      RectangleShape rs2 = new RectangleShape(60); 
      RectangleShape rs3 = new RectangleShape(40, 20); 
      System.out.println("First rectangle : " + rs1.getArea()); 
      System.out.println("Second rectangle : " + rs2.getArea()); 
      System.out.println("Third Rectangle : " + rs3.getArea());
   }
}


Output:

First rectangle : 12.0
Second rectangle : 1200.0
Third Rectangle : 800.0

Also read – find area of rectangle in java using method