Page 136 - CTS - CSA TP - Volume 2
P. 136
COMPUTER SOFTWARE APPLICATION - CITS
EXERCISE 98 : Create and use Overloaded methods in
JAVA
Objectives
At the end of this exercise you shall be able to
• know overloaded methods in JAVA
• develop Java programs using overloaded methods.
Requirements
Tools/Materials
• PC / laptop with windows OS
• SDK software
• Test editor (Visual studio/ subline/ notepad)
Overloaded methods in Java are methods that have the same name but different parameter lists. Here are
a few examples demonstrating the creation and usage of overloaded methods:
Procedure
TASK 1: Calculating the Area of Shapes
// Area of Shapes using overloaded methods
import java.io.*;
public class GeometricalShapes {
// Method to calculate the area of a square
public static double calculateArea(int side) {
return side * side;
}
// Method to calculate the area of a rectangle
public static double calculateArea(long length, long width) {
return length * width;
}
// Method to calculate the area of a circle
public static double calculateArea(double radius) {
return Math.PI * radius * radius;
}
// Method to calculate the area of a triangle
public static double calculateArea(double base, double height) {
return 0.5 * base * height;
}
121