Page 137 - CTS - CSA TP - Volume 2
P. 137
COMPUTER SOFTWARE APPLICATION - CITS
public static void main(String[] args) {
int side = 5;
long length =6L;
long width = 4L;
double radius = 3.0;
double base = 8.0;
double height = 5.0;
// Calculate areas using overloaded methods
System.out.println(“Area of square: “ + calculateArea(side));
System.out.println(“Area of rectangle: “ + calculateArea(length, width));
System.out.println(“Area of circle: “ + calculateArea(radius));
System.out.println(“Area of triangle: “ + calculateArea(base, height));
}
}
Explanation:
1 Method Overloading:
• The program uses method overloading to define multiple versions of the calculateArea method with
different parameter types or numbers.
• This allows the same method name to be used for calculating the area of various geometrical shapes.
2 Calculate Area of a Square:
• The first overloaded method, calculateArea(int side), is designed to calculate the area of a square.
• It takes an integer parameter (side) representing the side length and returns the calculated area using the
formula side * side.
3 Calculate Area of a Rectangle:
• The second overloaded method, calculateArea(long length, long width), is tailored for calculating the area
of a rectangle.
• It takes two long integer parameters (length and width) representing the length and width, and returns the
calculated area using the formula length * width.
4 Calculate Area of a Circle:
• The third overloaded method, calculateArea(double radius), is specialized for calculating the area of a
circle.
• It takes a double parameter (radius) representing the radius and returns the calculated area using the
formula Math.PI * radius * radius.
5 Calculate Area of a Triangle:
• The fourth overloaded method, calculateArea(double base, double height), is designed for calculating the
area of a triangle.
• It takes two double parameters (base and height) representing the base and height, and returns the
calculated area using the formula 0.5 * base * height.
6 Main Method:
• In the main method, sample values for the dimensions of a square, rectangle, circle, and triangle are
declared.
• The overloaded methods are then called with these values to calculate and print the areas of the
respective shapes.
122
CITS : IT & ITES - Computer Software Application - Exercise 98