Method Overloading Java Program

Method overloading is a feature in Java that allows you to define multiple methods with the same name but different parameters. In this article, we will discuss how to write a Java program that demonstrates method overloading.

To overload a method in Java, we need to define multiple methods with the same name in the same class. The methods should differ in their number or types of parameters. Here is an example of a Java program that demonstrates method overloading:

public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }

    public double add(double a, double b) {
        return a + b;
    }

    public int add(int a, int b, int c) {
        return a + b + c;
    }

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

        int result1 = calculator.add(5, 10);
        double result2 = calculator.add(3.5, 4.5);
        int result3 = calculator.add(2, 4, 6);

        System.out.println("Result 1: " + result1);
        System.out.println("Result 2: " + result2);
        System.out.println("Result 3: " + result3);
    }
}

Let’s break down this code line by line.

  • The first line defines a public class named Calculator.
  • The next three lines define three methods with the same name, add, but different parameter lists. The first method takes two integers as parameters and returns their sum. The second method takes two doubles as parameters and returns their sum. The third method takes three integers as parameters and returns their sum.
  • Inside the main() method, we create a new Calculator object named calculator.
  • We call each version of the add() method and assign the results to three different variables.
  • We output the results using the System.out.println() method.

When we run this program, the output will be:

Result 1: 15
Result 2: 8.0
Result 3: 12

This program demonstrates how to use method overloading in Java to define multiple methods with the same name but different parameter lists. Method overloading is a powerful feature in Java that allows you to write more concise and expressive code by providing different ways to call a method. By understanding the basics of Java syntax and method overloading, you can create more complex programs that work with a wide variety of data types and parameters.