Java Program to find area of different shapes using inheritance
Program
import java.util.*;
interface AreaPerimeter
{
float calculateArea(float x, float y);
float calculatePerimeter(float a, float b);
}
class Rectangle implements AreaPerimeter
{
public float calculateArea(float x, float y)
{
float area = x * y;
return area;
}
public float calculatePerimeter(float a, float b)
{
float perimeter = (2 * a) + (2 * b);
return perimeter;
}
}
class Triangle implements AreaPerimeter
{
public float calculateArea(float x, float y)
{
float area = (float) 0.5 * x * y;
return area;
}
public float calculatePerimeter(float a, float b)
{
float perimeter = 2 * (float) Math.PI * a;
return perimeter;
}
}
public class FindAreaInheritance
{
public static void main(String[] args)
{
float area, perimeter;
Scanner sc = new Scanner(System.in);
System.out.println("Enter value of a:");
float a = sc.nextFloat();
System.out.println("Enter value of b:");
float b = sc.nextFloat();
Rectangle rect = new Rectangle();
area = rect.calculateArea(a, b);
perimeter = rect.calculatePerimeter(a, b);
System.out.println("Rectangle");
System.out.println("Area:\t" + area);
System.out.println("Perimeter:\t" + perimeter);
Triangle triangle = new Triangle();
area = triangle.calculateArea(a, b);
perimeter = triangle.calculatePerimeter(a, b);
System.out.println("Triangle");
System.out.println("Area:\t" + area);
System.out.println("Perimeter:\t" + perimeter);
sc.close();
}
}
Output
Enter value of a:
5
Enter value of b:
8
Rectangle
Area: 40.0
Perimeter: 26.0
Triangle
Area: 20.0
Perimeter: 31.415928