Function Overloading in Java


☞If a class have multiple methods by same name but different parameters, it is known as method overloading.

☞If we have to perform only one operation, having same name of the methods increases the readability of the program.

☞There are two ways to overload the method in java.

1.  By changing number of arguments 
2.  By changing the data type
Note : Method Overloading is not possible by changing the return type of the method.

Changing Number Of Arguments

☞We can overload a function by changing the number of arguments.

☞Data types of the data may be same or different.

Example

class Addition{
    
    void sum(int a, int b){
        System.out.println(a+b);
    }

    void sum(int a, int b,int c){
        System.out.println(a+b+c);
    }
    
    public static void main(String args[]){
        Addition obj=new Addition();
        obj.sum(5,6);
        obj.sum(5,6,4);
    }
    
}

Output

11
15

Changing The Data Type

☞We can overload a function by changing the datatype of data if number of arguments are same.

☞Number of arguments can be different also.

Example

class Addition{
    
    void sum(int a, int b){
        System.out.println(a+b);
    }

    void sum(double a, double b){
        System.out.println(a+b);
    }
    
    public static void main(String args[]){
        Addition obj=new Addition();
        obj.sum(5,6);
        obj.sum(5.5,6.5);
    }
    
}

Output

11
12.0