Area of rectangle using constructor overloading in java

Hey guys!! Welcome to flower brackets blog. In this post let’s learn area of rectangle using constructor overloading in java.

Area of rectangle using constructor overloading in java

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.

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

Let’s see java program to calculate area of rectangle using constructor overloading,

class RectangleShape 
{
int length, breadth;
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

Related Posts