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:

  1. We define a class called Area.
  2. Inside the Area class, we have two methods with the same name calculateArea, but they differ in the number and types of parameters. This is method overloading.
  3. The first calculateArea method takes two parameters (length and width) and calculates the area of a rectangle.
  4. The second calculateArea method takes one parameter (radius) and calculates the area of a circle.
  5. In the main method, we create an object areaCalculator of the Area class.
  6. We call the calculateArea method with different sets of arguments to calculate the area of both a rectangle and a circle.
  7. 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

20+ Interview Questions on Go Programming Language

Java Practice Exercise

programmingempire

Princites