Method Overloading in Java

(Last Updated On: March 19, 2019)

Learn method overloading in java with simple example.

Method Overloading

Having multiple methods with same name in java programming is known as Method overloading. It is also known as compile time polymorhism in java.

In other word, a class has multiple methods with same name. For example, below class “Paint” has three methods with same name i.e. “Color”. Notice that all the methods have different number of arguments.

Note that if all methods with same name have same number of arguments, then there data types must be different. Method overloading same as constructor overloading in java.

 

Definition: “Multiple methods in a class with same name having different parameters or data types is known as method overloading”.

You can see here a screen shot taken from eclipse for String class valueOf() overloaded method in java framework.

java method overloading
java method overloading

Think, if valueOf method wouldn’t have overloaded, then it would have looked like below, which is not clean, ugly and more difficult to read than above overloaded one.

 

Java Method Overloading Example

Below class Painting has three overloaded methods named color.

Output:
Default-color= black
Color1= green
Color1= green Color2= yellow
Color1= green Color2= yellow Color3= blue

NOTE:

Method overloading comes under compile time polymorphism. Recommend to read why method overloading is called compile time polymorphism. In the link, both run time and compile time has been explained with simple example.