Method Overloading

suggest change

Method overloading, also known as function overloading, is the ability of a class to have multiple methods with the same name, granted that they differ in either number or type of arguments.

Compiler checks method signature for method overloading.

Method signature consists of three things -

  1. Method name
  2. Number of parameters
  3. Types of parameters

If these three are same for any two methods in a class, then compiler throws duplicate method error.

This type of polymorphism is called static or compile time polymorphism because the appropriate method to be called is decided by the compiler during the compile time based on the argument list.

class Polymorph {

    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;
    }

    public static void main(String... args){
        Polymorph poly = new Polymorph();
        int a = 1, b = 2, c = 3;
        float d = 1.5, e = 2.5;

        System.out.println(poly.add(a, b));
        System.out.println(poly.add(a, b, c));
        System.out.println(poly.add(d, e));
    }

}

This will result in:

2
6
4.000000

Overloaded methods may be static or non-static. This also does not effect method overloading.

public class Polymorph {

    private static void methodOverloaded()
    {
        //No argument, private static method
    }
 
    private int methodOverloaded(int i)
    {
        //One argument private non-static method
        return i;
    }
 
    static int methodOverloaded(double d)
    {
        //static Method
        return 0;
    }
 
    public void methodOverloaded(int i, double d)
    {
        //Public non-static Method
    }
}

Also if you change the return type of method, we are unable to get it as method overloading.

public class Polymorph {  

void methodOverloaded(){
    //No argument and No return type
}
int methodOverloaded(){
    //No argument and int return type 
    return 0;
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Polymorphism:
* Method Overloading

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
51 Polymorphism
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap