Design a class to overload a function area( ) as follows:

  1. double area (double a, double b, double c) with three double arguments, returns the area of a scalene triangle using the formula:
    area = √(s(s-a)(s-b)(s-c))
    where s = (a+b+c) / 2
  2. double area (int a, int b, int height) with three integer arguments, returns the area of a trapezium using the formula:
    area = (1/2)height(a + b)
  3. double area (double diagonal1, double diagonal2) with two double arguments, returns the area of a rhombus using the formula:
    area = 1/2(diagonal1 x diagonal2)

Java Programming Language (Article) (Program)

13

Given Input:


Expected Output:


Program:

import java.util.Scanner;

public class RAnsariOverload {

    // Method to calculate the area of a triangle using Heron's formula
    double area(double a, double b, double c) {
        double s = (a + b + c) / 2;
        double x = s * (s - a) * (s - b) * (s - c);
        double result = Math.sqrt(x);
        return result;
    }
    
    // Method to calculate the area of a trapezoid
    double area(int a, int b, int height) {
        double result = (1.0 / 2.0) * height * (a + b);
        return result;
    }
    
    // Method to calculate the area of a rhombus
    double area(double diagonal1, double diagonal2) {
        double result = 1.0 / 2.0 * diagonal1 * diagonal2;
        return result;
    }

    // Main method to test the overloaded area methods
    public static void main(String[] args) {
        RAnsariOverload geometry = new RAnsariOverload();
        
        // Test area calculation for a triangle
        double triangleArea = geometry.area(3.0, 4.0, 5.0);
        System.out.println("Triangle Area: " + triangleArea);
        
        // Test area calculation for a trapezoid
        double trapezoidArea = geometry.area(5, 7, 4);
        System.out.println("Trapezoid Area: " + trapezoidArea);
        
        // Test area calculation for a rhombus
        double rhombusArea = geometry.area(6.0, 8.0);
        System.out.println("Rhombus Area: " + rhombusArea);
    }
}

Output:

Triangle Area: 6.0
Trapezoid Area: 24.0
Rhombus Area: 24.0
Press any key to continue . . .


This Particular section is dedicated to Programs only. If you want learn more about Java Programming Language. Then you can visit below links to get more depth on this subject.