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.

 

Advertisements

4 thoughts on “Method Overloading in Java with example

  1. Thanks for some other magnificent post. Where else may anybody get that type of info in such an ideal way of writing? I have a presentation subsequent week, and I am at the search for such info.

    Like

  2. It’s really a nice and helpful piece of information. I’m glad that you just shared this helpful info with us. Please keep us informed like this. Thanks for sharing.

    Like

  3. I do consider all the concepts you’ve offered for your post. They are very convincing and can certainly work. Nonetheless, the posts are very quick for beginners. Could you please prolong them a bit from next time? Thanks for the post.

    Like

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 )

Google+ photo

You are commenting using your Google+ 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 )

w

Connecting to %s