In Java, it is possible to define two or more methods of same name in a class, provided that there argument list or parameters are different. This concept is known as Method Overloading.
If a class have multiple methods by same name but different parameters, it is known as Method Overloading.
If we have to perform only one operation, having same name of the methods increases the readability of the program.Different ways to overload the method
There are three ways to overload the method in java
- By changing number of arguments
- By changing the data type
- Sequence of Data type of parameters.
Method overloading is also known as Static Polymorphism.
1)Example of Method Overloading by changing the no. of arguments
In this example, we have created two overloaded methods, first sum method performs addition of two numbers and second sum method performs addition of three numbers.
class Calculation{ void sum(int a,int b){System.out.println(a+b);} void sum(int a,int b,int c){System.out.println(a+b+c);} public static void main(String args[]){ Calculation obj=new Calculation(); obj.sum(10,10,10); obj.sum(20,20); } } Output:30 40
2)Example of Method Overloading by changing data type of argument
In this example, we have created two overloaded methods that differs in data type. The first sum method receives two integer arguments and second sum method receives two double arguments.
class Calculation2{ void sum(int a,int b){System.out.println(a+b);} void sum(double a,double b){System.out.println(a+b);} public static void main(String args[]){ Calculation2 obj=new Calculation2(); obj.sum(10.5,10.5); obj.sum(20,20); } } Output:21.0 40
3)Example Overloading – Sequence of data type of arguments
Here method disp() is overloaded based on sequence of data type of arguments – Both the methods have different sequence of data type in argument list. First method is having argument list as (char, int) and second is having (int, char). Since the sequence is different, the method can be overloaded without any issues.
class DisplayOverloading3 { public void disp(char c, int num) { System.out.println("I’m the first definition of method disp"); } public void disp(int num, char c) { System.out.println("I’m the second definition of method disp" ); } } class Sample3 { public static void main(String args[]) { DisplayOverloading3 obj = new DisplayOverloading3(); obj.disp('x', 51 ); obj.disp(52, 'y'); } } Output: I’m the first definition of method disp I’m the second definition of method disp