Method Overloading in Java with Examples
Method Overloading in Java
Method overloading in Java is a feature which makes it possible to use the same method name to perform different tasks. In this tutorial post we will Understand the concept of Java Method Overloading. In the previous post, we understood what are methods in java so if you have missed that post you can check it out.
If a class has multiple methods having same name but different in parameters, it is known as Method Overloading. Overloading allows different methods to have same name, but different signatures where signature can differ by number of input parameters or type of input parameters or order of input parameters. Overloading is related to compile time (or static) polymorphism (we will understand polymorphism in other tutorial).
Lets, take an example situation to understand –
Suppose you have a program to perform addition of numbers and you create a method to add 2 numbers as – add(int x, int y). Now you have a new requirement to add 3 numbers so you again create a new method as – add3(int x, int y, int z). But now again you have one more new requirement to add 4 numbers. You see the hassle here right ? every time you get this requirement you have to find a new method name. But the underlying logical operation is the same right ? cause in the end we are anyways going to perform addition. So why use different method names. So that is where method overloading comes to the rescue.
Advantage of method overloading
Method overloading increases the readability of the program.
Different ways to overload the method
There are 3 ways to overload the method in java
- By changing number of arguments
- By changing the data type
- By changing the order of arguments (if different datatypes are involved)
Example of Method Overloading in Java
public class MethodOverloading { //1) 2 arguments int & double double add(int x, double y) { return(x+y); } //2) 2 arguments but different order - double & int double add(double x, int y) { return(x+y); } //3) 3 arguments double add(double x, int y, float z) { return(x+y+z); } public static void main(String[] args) { // TODO code application logic here int a=5; double b = 7.5; float c = 4.5f; double result; MethodOverloading obj = new MethodOverloading(); result = obj.add(b, a); // 1st add function System.out.println("Addtion is: "+result); result = obj.add(a, b); // 2nd add function System.out.println("Addtion is: "+result); result = obj.add(b,a,c); // 3rd add function System.out.println("Addtion is: "+result); } }
Addtion is: 12.5
Addtion is: 17.0
Pingback: Polymorphism in Java - Method Overloading | Method Overriding