What is method overloading in Java?
If two or more methods in a class have same name but different parameters, it is known as method overloading. Method overloading is one of the ways through which java supports polymorphism. Method overloading can be done by changing number of arguments or by changing the data type of arguments. If two or more method have same name and same parameter list but differs in return type then they are not said to be overloaded method.
Different ways of Method overloading
1. Method overloading by changing data type of Arguments
In this example, you can see that sum() method is overloaded two times differing in data type. The first sum() method receives two integer arguments and second sum() method receives two double arguments.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class Addition{ void sum(int a, int b) { System.out.println("Sum is "+(a+b)); } void sum(double a, double b) { System.out.println("Sum is "+(a+b)); } public static void main (String[] args) { Addition add = new Addition(); add.sum (8, 5); //sum(int a, int b) is method is called. add.sum (4.5, 3.5); //sum(double a, double b) is called. } } |
1 2 3 |
Output: Sum is 13 Sum is 8.0 |
2. Method overloading by changing no. of argument.
In the below example the find() method is overloaded twice. The first takes two arguments to calculate area, and the second takes three arguments to calculate area.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class Addition{ void sum(int l, int b) { System.out.println("Sum is "+(l+b)) ; } void sum(int l, int b,int h) { System.out.println("Sum is "+(l+b+h)); } public static void main (String args[]) { Addition add = new Addition(); add.sum(8,5); //sum(int l, int b) is method is called. add.sum(4,6,2); //sum(int l, int b,int h) is called. } } |
1 2 3 |
Output: Sum is 13 Sum is 12 |
When an overloaded method is called java look for match between the arguments to call the method and the method’s parameters. This match need not always be exact, sometime when exact match is not found, Java automatic type conversion plays a vital role.
…continued in the next article Method overloading in Java – Part 2