Method Overloading:
Method Overloading is achieved by same method name but differ in parameters. The main usage of Method Overloading is consider you have to multiply some numbers. The methods are multiply(int,int) and multiply(double,int). Here the method name is same but arguments types are different.One for two int variables and the other for int and double. By giving the same name the programmer is easy identification that these methods are for multiplying numbers.
Method Overloading is again classified into two types.
- differ in number of arguments
- differ in the datatype of arguments.
Differ in Number of Arguments:
In this type of overloading the number of arguments in the method changes.That is the multiplication example seen previously.
Example Program by Changing the number of arguments:
package com.jobberindia;
import java.io.File;
import java.util.*;
public class HelloWorld {
void multiply(int a,int b)
{
int c = a*b;
System.out.println("After multiplication of "+a+" and "+b+"is: "+c);
}
void multiply(int a,int b,int c)
{
int d = a*b*c;
System.out.println("After multiplication of "+a+","+b+" and "+c+"is: "+d);
}
public static void main(String[] args) {
HelloWorld hw = new HelloWorld();
hw.multiply(5, 3);
hw.multiply(5, 6, 7);
}
}
Output:
After multiplication of 5 and 3is: 15
After multiplication of 5,6 and 7is: 210
Differ in changing the data type of arguments:
Another way to achieve Method Overloading is by changing the data type of arguments. The same multiplication example by changing the data type of arguments is shown below.
Example program by changing the data type of arguments:
package com.jobberindia;
import java.io.File;
import java.util.*;
public class HelloWorld {
void multiply(int a,int b)
{
int c = a*b;
System.out.println("After multiplication of"+a+" and "+b+"is: "+c);
}
void multiply(int a,double b)//one int and other double value
{
double c = a*b;
System.out.println("After multiplication of"+a+" and "+b+"is: "+c);
}
public static void main(String[] args) {
HelloWorld hw = new HelloWorld();
hw.multiply(5, 3);
hw.multiply(5, 6.6);
}
}