Method Overloading in Java

Method overloading is a feature in Java that allows a class to have multiple methods having the same name, but with different parameters (number, type, or both). It enhances code readability and reusability.

Rules for Method Overloading:

  • Methods must have the same name.
  • Methods must have a different number or type of parameters.
  • Return type is not considered for method overloading.

Example of Method Overloading:

Let's look at an example of a class with overloaded methods to calculate the area of different shapes:


public class GeometryCalculator {

  // Method to calculate the area of a circle
  public double calculateArea(double radius) {
    return Math.PI * radius * radius;
  }

  // Method to calculate the area of a rectangle
  public double calculateArea(double length, double width) {
    return length * width;
  }

  // Method to calculate the area of a triangle
  public double calculateArea(double base, double height) {
    return 0.5 * base * height;
  }

}

Method Overloading in Action:

Now, let's use the GeometryCalculator class to calculate areas for different shapes:


public class Main {

  public static void main(String[] args) {
    GeometryCalculator calculator = new GeometryCalculator();

    double circleArea = calculator.calculateArea(5.0);
    double rectangleArea = calculator.calculateArea(4.0, 6.0);
    double triangleArea = calculator.calculateArea(3.0, 8.0);

    // Use the calculated areas as needed
  }

}

Note:

Method overloading allows the use of the same method name for different tasks, making the code more intuitive and easy to read. It is a powerful tool for creating more flexible and expressive code.