Overloading Methods in Java

Java allows you to create two or more method with the same name but with different signatures. The signature includes the numbers, type, and the sequence of the arguments passes to a method. This capability to overload a method is referred to as overloading methods.

Example1:

// Welcome to CodeParent.com
// Example for Overloading
public class Addition {
//Method name sum with 2 int parameters
static int sum(int x, int y) {
return (x + y);
}
//Methos name sum with 3 parameters like float, int, float
static float sum(float x, int y, float z) {
return (x + y + z);
}
public static void main(String[] args) {
int a = sum(5, 5);
float b = sum(10.50f, 20, 10.50f);
System.out.println("Calling the sum(int,int) " + a);
System.out.println("Calling the sum(float, int, float) " + b);
}
}

Output:
Calling the sum(int,int) 10
Calling the sum(float, int, float) 41.0

Point to remember:

  • Note that in the above program all the methos are declared as static, thus they are called in main method without using objects.
  • Leave a Reply