SEMrush

Method Overloading in Java - Easy Explanation with Examples


Method Overloading Function overloading or method overloading is the ability to create multiple methods of the same name with different implementations.

It is a feature that allows a class to have two or more methods having same name but different number of arguments or different argument types or different lines of code , calculations etc inside the methods with same name.
If a class have multiple methods by same name but different parameters, it is known as Method Overloading.
We can overload main() method also .
Yes, by method overloading. You can have any number of main methods in a class by method overloading.
Method overloading increases the readability of the program.
There are three ways to overload method in java
1.    By changing number of arguments
2.    By changing the data type
3.    By changing the sequence of data type of parameters.
Method Overloading is NOT possible by changing the return type of the method.
Method overloading is also known as Static Polymorphism.
Key Points:
1. Static Polymorphism is also known as early binding or compile time binding as it happens at compile time.
2. Method overloading is an example of static binding because binding of method call to its definition happens at Compile time.
Constructor method can also be oveloaded same way.
Constructor overloading allows a class to have more than one constructors having different argument lists.
Example :
class OverLoadDataTypes
{
    public void see1(char a)
    {
        System.out.println(a);
    }
    public void see2(int a)
    {
       System.out.println(a);
   }

} 

class UsingMethods
{
    public static void main(String args[])
    {
        OverLoadDataTypes obj = new OverLoadDataTypes();
        obj.see('l');
        obj.see(7);
    }

Comments

Hitesh Kumar said…

Method Overloading in Java Nice post, thanks on Method Overloading in Java - Easy Explanation with Examples