Method Overloading in Java with example

Method overloading in java means that a class can have two or more methods of same name if the argument lists that the method holds are different. Method overloading is also called static polymorphism. The example below shows how we can overload a method.


class MethodOverloading {
public int Sum(int a, int b){
int c = a + b;
return c;
}

public int Sum(int a, int b, int c){
int d = a+b+c;
return d;

}
public double Sum(double a, double b, double c, double d){

double e = a+b+c+d;
return e;
}


}
class Result{
public static void main(String[] args){

MethodOverloading obj1 = new MethodOverloading();

System.out.print(obj1.Sum(3.4, 4.2, 6.7, 8.4));
}
}

OUTPUT:

22.700000000000003

In the above example when the there are three methods of same name Sum() but the parameters  of these methods are different and they will return different values. So, when we give the arguments as two integers, it will execute first method, if we give parameters as three integers it will execute second method and if we give parameters as four doubles it will execute the third method.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s