The following code shows an Example of Method Overloading in Java.
Problem Statement
Write a program to create a class Area and calculate the area of the rectangle and circle using method overloading.
Solution
class Area {
// Method to calculate the area of a rectangle
double calculateArea(double length, double width) {
return length * width;
}
// Method to calculate the area of a circle
double calculateArea(double radius) {
return Math.PI * radius * radius;
}
}
public class AreaCalculator {
public static void main(String[] args) {
// Create an object of the Area class
Area areaCalculator = new Area();
// Calculate and print the area of a rectangle
double rectangleArea = areaCalculator.calculateArea(5.0, 3.0);
System.out.println("Area of the rectangle: " + rectangleArea);
// Calculate and print the area of a circle
double circleArea = areaCalculator.calculateArea(2.5);
System.out.println("Area of the circle: " + circleArea);
}
}
In this Java program:
- We define a class called
Area
. - Inside the
Area
class, we have two methods with the same namecalculateArea
, but they differ in the number and types of parameters. This is method overloading. - The first
calculateArea
method takes two parameters (length and width) and calculates the area of a rectangle. - The second
calculateArea
method takes one parameter (radius) and calculates the area of a circle. - In the
main
method, we create an objectareaCalculator
of theArea
class. - We call the
calculateArea
method with different sets of arguments to calculate the area of both a rectangle and a circle. - Finally, we print the calculated areas for the rectangle and circle.
When you run this Java program, it will calculate and display the areas of the rectangle and circle using method overloading.
Further Reading
Spring Framework Practice Problems and Their Solutions
From Google to the World: The Story of Go Programming Language
Why Go? Understanding the Advantages of this Emerging Language
Creating and Executing Simple Programs in Go