Method Overloading in Java


Method overloading, also known as function overloading, is the ability of a class to have multiple methods with the same name, granted that they differ in either number or type of arguments. Compiler checks method signature for method overloading.

Method signature consists of three things :

  • Method name
  • Number of parameters
  • Types of parameters

The program demonstrates the concept of method overloading in Java.

  • In this program, a class named MathOperation is created with four overloaded methods named multiply. These methods perform multiplication operations on different types of data.
  • The first multiply method accepts two integer parameters and returns their product. The second multiply method accepts two double parameters and returns their product. The third multiply method accepts one double and one integer parameter and returns their product. The fourth multiply method accepts a single integer parameter and returns its square.
  • In the main method of the methodOverloading class, we call these four methods with different arguments and display the results using System.out.println.

Source Code

//Method Overloading in  Java
class MathOperation {
    public static int multiply(int a, int b) {
        return a * b;
    }
    public static double multiply(double x, double y) {
        return x * y;
    }
    public static double multiply(double i, int j) {
        return i * j;
    }
    public static int multiply(int r) {
        return r*r;
    }
}
public class methodOverloading {
    public static void main(String arg[]) {
        System.out.println("Multiply 2 Integer Value : " + MathOperation.multiply(25, 10));
        System.out.println("Multiply 2 Double Value : " + MathOperation.multiply(2.5, 8.5));
        System.out.println("Multiply Double & Integer Value : " + MathOperation.multiply(2.5, 8));
        System.out.println("Multiply Integer Value : " + MathOperation.multiply(2));
    }
}
 

Output

Multiply 2 Integer Value : 250
Multiply 2 Double Value : 21.25
Multiply Double & Integer Value : 20.0
Multiply Integer Value : 4
To download raw file Click Here

Basic Programs