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

These types of polymorphism are called static or compile time polymorphism because the appropriate method to be called is decided by the compiler during the compile time based on the argument list.

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