Menu
Topics Index
...
`


Methods Overiding, Overloading >
Siva Nookala - 14 Mar 2016
Method overloading can be achieved by defining multiple methods in the same class with the method name being same but the parameters are different.

In the below class ArithmeticUtils we have defined 5 methods out of which three methods have the name add and two methods have the name multiply. As discussed in Java Methods, there is no problem in having the same method name for one or more methods as long as the method signature is different. The method signature includes the return type, method name and the parameters. As long as the parameters are different (the type, number and the order of the parameters) it is allowed to create as many methods with the same method name.
class ArithmeticUtils
{
    int add(int a, int b)    // LINE A
    {
        return a + b;
    }

    int add(int a, int b, int c) // LINE B
    {
        return a + b + c;
    }

    double add(double a, double b, double c) // LINE C
    {
        return a + b + c;
    }

    int multiply(int a, int b)
    {
        return a * b;
    }

    int multiply(int a, int b, int c)
    {
        return a * b * c;
    }
}
Here the add method is overloaded once with two int parameters (LINE A), once with three int parameters (LINE B) and once with three double parameters (LINE C). We can define more methods with the same name add as long as the parameters are different. The following methods can be defined.
double add(int a, double b)
{
    return a + b;
}

double add(int a, double b, int c, double d)
{
    return a + b + c + d;
}
But having a method with same parameters and different return type is not allowed. The below methods are not allowed, since the parameters are same and only the return type is different.
int add(int a, int b)
{
    return a + b;
}

double add(int a, int b) // NOT ALLOWED
{
    return a + b;
}
Similarly, the parameter names are of no importance and having two methods with same parameter type and order, but with different parameter names are not allowed.
int add(int a, int b)
{
    return a + b;
}

int add(int c, int d) // NOT ALLOWED
{
    return c + d;
}

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App