Overloaded methods in Java

Overloaded methods in Java are methods that have the same name but different the parameter list. In this tutorial, we will learn how to create and use the overloaded methods in Java.

Some of the guidelines below for defining our overloaded methods are:

  • Overloaded methods must be of the same name but differ in parameters.
  • They can be defined with the same or different types of data returned.
  • They can be defined the same or different access modifier.
  • Methods are not called overloaded if they differ only in the return data type or access modifier.

In the example below we have two overloaded methods named printMessage():

And the same parameter, but the data types of those parameters are different: a String type, an int type.


Parameters in overloaded methods

The list of parameters in the overloaded methods must be different, which means:

  • The number of parameters is different.

For example:

  • The number of parameters may be the same but different in terms of data type in order of parameter list.

For example:

One thing to keep in mind is that there are data types that can be converted to other types of data, for example from int to double, so even though we can declare overloaded methods with them, there are cases where we will have compile errors.

For example, we have two printMessage() methods defined as follows:

But when used in the case below, will be compile error:

Overloaded methods in Java

Since the int type can be converted to double, in this case, the compiler does not know what method we are calling.

To be usable, we need to explicitly declare the type of data we pass into:

Overloaded methods in Java


Data type returned

Methods are not called overloaded if they differ only in the type of data returned and in this case our code cannot be compiled at all.

For example:

Overloaded methods in Java

Access modifier

Similar to the return data type, the methods are also not called overloaded if they differ only in the access modifier and our code also has a compile error if we define it as such.

For example:

Overloaded methods in Java

Add Comment