Java Method Overloading - The Coding Shala

Home >> Learn Java >> Java Method Overloading

Java Method Overloading

Java class can have more than one method with the same name but different in parameters, known as Method Overloading.

Question: What is the use of method overloading?
Answer: Suppose we want to perform some operation like an addition but addition can be performed between two numbers, three numbers or two floats or more. So instead of using different methods, we use the same name of the method with different parameters. This can increase the readability of the program.
Java Method Overloading - The Coding Shala
Method overloading can be achieved by changing numbers of arguments or by changing the data types.

Example of Method Overloading in Java

The following example explains Method Overloading:
//Method Overloading example
class Addition{
    public int add(int a, int b){
        return a+b;
    }
    public int add(int a, int b, int c){
        return a+b+c;
    }
    public float add(float a, float b){
        return a+b;
    }
}

class Main{
    public static void main(String[] args){
        Addition ad = new Addition();
        System.out.println(ad.add(1,2));
        System.out.println(ad.add(1,2,3));
        System.out.println(ad.add(1.4f,1.5f));
    }
}
Output:
3
6
2.9

Point to Remember: In Java, main() is also a method so we can have multiple numbers of main methods but JVM only calls the main(String[] args) method.

Note: In Method Overloading type promotion will be done automatically. A byte can be promoted to short, int, float, double. The int can be promoted to long. The char can be promoted to int, long and so on. 

Example of Method Overloading with TypePromotion in Java

The following example explains type promotion in Method Overloading:
//Method Overloading with typepromotion example
class Addition{
    public void add(int a, long b){
        System.out.println(a+b);
    }
    public void add(float a, float b, float c){
        System.out.println(a+b+c);
    }
}

class Main{
    public static void main(String[] args){
        Addition ad = new Addition();
        ad.add(1,3);
        ad.add(1,2,3);
        ad.add(1, 3, 3.5f);
    }
}
Output:
4
6.0
7.5

Method Overloading is related to compile-time or static polymorphism.

Note: In java, Methods cannot be overloaded according to the return type.

We cannot overload static methods if they only differ by static keyword and the number of parameters and types of parameters is the same.


Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Single Number 3 LeetCode Solution - The Coding Shala

LeetCode - Number of Good Pairs Solution - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala